2015-10-16 87 views
0

我目前正在處理我們的用戶配置文件。用戶可以將多個電子郵件地址添加到他/她的帳戶。Django ModelForm在提交提交後添加外鍵忽略

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") 

請注意我有一個自定義用戶模型。這不是問題。

我不太確定,爲什麼在第二次save()之前客戶字段沒有被填充。 CustomerEmails模型的表中目前沒有行。 (我知道這將在未來與.get()發生衝突,因爲用戶可以有多個電子郵件,但首先要做的事情)

回答

0

您需要設置模型實例的關係,從形式保存,而不是形式本身。

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

噢男孩。星期五..非常感謝。我在這裏瘋了,爲什麼這不起作用....所有的好感謝丹尼爾 – Richard