2011-03-06 41 views
-1

我有兩個模型用戶和客戶我在customer模型中有customer = models.ForeignKey(Customer,related_name ='orders'),我希望將用戶和客戶表單一起保存,如果在一種形式中存在錯誤,那麼兩者都不應該被保存。當我創建一個視圖來保存它,它給了我錯誤,mainsiteapp_customer.user_id可能不是NULL。user_id在django中可能不爲NULL

我曾嘗試一切可能的方式我的最終代碼如下 高清用戶窗體(請求):

if request.method == 'POST': 
    userform = UserForm(request.POST) 
    customerform = CustomerForm(request.POST)   
    if userform.is_valid(): 
    u = userform.save() 

     Customer.user = u 
     print Customer.user 
     if customerform.is_valid(): 
      c = customerform.save(commit=False)  

      try: 
       c.full_clean() 
       c.save() 
       print c 
       return HttpResponseRedirect('/webshop/') 
      except ValidationError, e: 
       pass 
     u.delete() 

else: 

    userform = UserForm() 
    customerform = CustomerForm() 
context = RequestContext(request, {'userform':userform, 'customerform':customerform,}) 
return render_to_response('userRegister.html', context) 

其現年9天,我無法找到其中m我做錯了。

如果有人知道其中m我做錯了 感謝

+0

「我有顧客= models.ForeignKey(客戶,related_name =‘訂單’)的客戶模型」你想自我加入?或者你的意思是在用戶模型中?你能發佈你的客戶和用戶模型嗎?您收到的錯誤表明您的客戶模型中沒有設置user_id fk – DTing 2011-03-06 11:29:12

回答

1
Customer.user = u 
if customerform.is_valid(): 
    c = customerform.save(commit=False) 

你設置模型的類變量user這裏。相反,您需要設置客戶的用戶屬性,如c.user = u

0

你只需要檢查,如果兩個用戶窗體和customerform使用的是和語句有效

def userForm(request): 

    if request.method == 'POST': 
     userform = UserForm(request.POST) 
     customerform = CustomerForm(request.POST)   
     if userform.is_valid() and customerform.is_valid(): 
      c = customerform.save() 
      u = userform.save(commit=False) 
      u.customer=c 
      u.save() 
      return HttpResponseRedirect('/webshop/') 
    else: 
     userform = UserForm() 
     customerform = CustomerForm() 
    context = RequestContext(request, {'userform':userform, 'customerform':customerform,}) 
    return render_to_response('userRegister.html', context) 
相關問題