开发者

user_id may not be NULL in django

i have two model User and Customer I have customer = models.ForeignKey(Customer, related_name='orders') in Customer model, I want both User and Customer form to be saved together and if there is error in one form then both shouldnt be saved. When i created a view to save both it has given me error that mainsiteapp_customer.user_id may not be NULL.

i have tried every possible way my final code is as below 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)

its now 9 days i couldnt find where m i doing wrong.

if someone know开发者_JAVA百科 where m i doing wrong thanks


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

You're setting the model's class variable user here. Instead you want to set the customer's user property like c.user = u.


You just need to check if both userform and customerform are valid using an and statement

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜