django中的user_id可能不是NULL

时间:2011-03-06 10:09:39

标签: python

我有两个型号用户和客户我在客户模型中有customer = models.ForeignKey(Customer,related_name ='orders'),我希望将用户和客户表单一起保存,如果一个表单中有错误则两者都不应该被保存。当我创建一个视图来保存它时,它给了我一个错误,即mainsiteapp_customer.user_id可能不是NULL。

我已经尝试了所有可能的方式,我的最终代码如下所示 def userForm(request):

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天我无法找到我做错的地方。

如果有人知道我做错了哪里 感谢

2 个答案:

答案 0 :(得分:1)

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

您在此处设置模型的类变量user。相反,您希望设置客户的用户属性,如c.user = u

答案 1 :(得分:0)

您只需使用和声明检查userform和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)