[英]Django gives IntergrityError, user.id NOT null, don't know why
I'm trying to make am modelform that is used to send an email to change the email on a user entry, and for some reason it gives me access_emailchangeauth.user_id may not be NULL
when I click submit on the form. 我正在尝试创建一个用于发送电子邮件以更改用户条目中的电子邮件的
access_emailchangeauth.user_id may not be NULL
,由于某种原因,当我单击表单上的access_emailchangeauth.user_id may not be NULL
时,它会给我access_emailchangeauth.user_id may not be NULL
。 I have no idea why. 我不知道为什么。
code is below 代码在下面
def changeEmail(request):
data = request.POST if request.method == 'POST' else None
if data:
form = ChangeEmailForm(data)
if form.is_valid():
form.save(user=request.user)
else:
a = request.user
a = u.objects.get(username__iexact=a)
form = UserModificationForm(instance=a)
form2 = ChangeEmailForm()
return render('accounts/modify.html',{'form': form, 'form2': form2, 'usr': a})
#forms.py
class ChangeEmailForm(ModelForm):
class Meta:
model = EmailChangeAuth
fields = ['new_email']
def save(self, *args, **kwargs):
user = kwargs.pop('user')
self.user = user
print user
super(ChangeEmailForm, self).save(*args, **kwargs)
#models.py
class EmailChangeAuth(models.Model):
auth_code = UUIDField(auto=True, unique=True)
user = models.ForeignKey(u)
new_email = models.EmailField(max_length=256)
def __unicode__(self):
return unicode(self.auth_code)
Since you have not included user in the list of fields, it will not be passed on to the ModelForm's instance constructor. 由于您没有将用户包括在字段列表中,因此不会将其传递给ModelForm的实例构造函数。
Thus, what you want here is to change the user attribute of the form's instance, not the attribute on the form object itself. 因此,您想要的是更改表单实例的用户属性,而不是表单对象本身的属性。 In .save(), change self.user to self.instance.user.
在.save()中,将self.user更改为self.instance.user。 That should get you going.
那应该让你走。
However, I also want to suggest that this mechanism it generally an anti-pattern: why are you not allowing user to be a field on the ModelForm if it's a required field that you populate anyway? 但是,我还想建议这种机制通常是一种反模式:为什么无论如何,如果您要填充的是必填字段,为什么不允许用户成为ModelForm上的字段?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.