在将对象保存到DB上时,我需要对等用户的身份验证。我需要这个,只是因为如果我让模型像使用外键一样,基本上用户可以更改它;因此,在保存对象时,我们可以有其他用户等。
因此,我将模型从user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True)
更改为
user = models.CharField(max_length=80,blank=True, null=True)
并放置以下行:
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
if not obj:
user = request.user
form.base_fields['user'].initial = user.user
form.base_fields['email'].initial = user.email
return form
AttributeError at /admin/parcare/parking/add/
'User' object has no attribute 'user'
我在做什么错了?
停车类(models.Model):
PARKING_PLOT = (
('P1', 'Parking #1'),('P2', 'Parking #2'), ('P3', 'Parking #3'),
('P4', 'Parking #4'),('P5', 'Parking #5'), ('P6', 'Parking #6'),
('P7', 'Parking #7'),('P8', 'Parking #8'), ('P9', 'Parking #9'),
('P10', 'Parking #10'),('P11', 'Parking #11'), ('P12', 'Parking #12'),
('P13', 'Parking #13'),('P14', 'Parking #14'), ('P15', 'Parking #15')
)
# user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True)
user = models.CharField(max_length=80,blank=True, null=True)
email = models.EmailField(blank=True, null=True)
parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True,help_text='Please select the date you want to come in the office.',)
parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True,help_text='Please select the date when you leave')
numar_masina = models.CharField(max_length=8, default="IF77WXV", blank=True, null=True,help_text='Please insert your license plate number')
location = models.CharField(max_length=3, blank=True, default="P1", null=True, choices=PARKING_PLOT,help_text='Please select the desired parking plot.')
updated = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True, null=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True, null=True)
答案 0 :(得分:0)
我认为您尝试使用user.user
会引起问题。 request.user
中的用户类没有这样的属性。相反,您可以使用user.username
并将其保存到以下表单中:
form.base_fields['user'].initial = user.username
。
可以找到用户模型参考here。