Django ModelForm在帖子提交后忽略添加外键

时间:2015-10-16 14:08:33

标签: python django

我目前正在处理我们的用户个人资料。用户可以将多个电子邮件地址添加到他/她的帐户。

views.py

@login_required(login_url='/login')
def profile_update_emails(request):
    context = {}
    ...
    try:
        email = CustomerEmails.objects.get(customer=request.user)
        update_emails_form = UpdateEmailsForm(request.POST or None, instance=email)
    except CustomerEmails.DoesNotExist:
        update_emails_form = UpdateEmailsForm(request.POST or None)
    context.update({'update_emails_form': update_emails_form})

    if request.POST:
        if update_emails_form.is_valid():
            update_emails_form.save(commit=False)
            update_emails_form.customer = request.user
            update_emails_form.save()
            messages.success(request, "All good")

return render(request, 'usercp/profile.html', context)

forms.py

class UpdateEmailsForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        for f in self.fields:
            self.fields[f].widget.attrs['class'] = 'form-control'

    class Meta:
        model = CustomerEmails
        fields = ('email',)

models.py

class CustomerEmails(models.Model):
    customer = models.ForeignKey(Customer)
    email = models.CharField(max_length=255, unique=True)

错误/迹:

IntegrityError at /usercp/profile/profile_update_emails
(1048, "Column 'customer_id' cannot be null")

请注意我有自定义用户模型。这不是问题所在。

我不太确定,为什么客户字段在第二次保存()之前没有填充。该表中目前没有CustomerEmails模型的行。 (我知道这将在未来与.get()发生冲突,因为用户可以拥有多封电子邮件,但首先要做的事情)

1 个答案:

答案 0 :(得分:0)

您需要在模型实例上设置关系,该关系从表单保存返回,而不是在表单本身上。

    obj = update_emails_form.save(commit=False)
    obj.customer = request.user
    obj.save()