简体   繁体   中英

Multiple ModelForm in Django

I have something like that in models.py

class A(models.Model):
   name = CharField(max_length=150)
class B(models.Model):
    a= ForeignKey(A)
    name =  CharField(max_length=150)

and i created modelform for both in views.py

def create(request):
     a_form = AForm()
     b_form = BForm()
     if request.method == 'POST':
          a_form = AForm(request.POST, prefix="a")
          b_form  = BForm(request.POST, prefix="b")
     if a_form.is_valid() and b_form.is_valid():
          a = a_form.save()
          b_form.cleaned_data["a"] = a
          b= b_form.save()
          return HttpResponseRedirect('/companies/detail/{b.id}')
     return render_to_response('companies/signup.html',{'AForm':a_form , 'BForm': b_form }, context_instance=RequestContext(request))

and i got this error

Exception Value: mysite_b.a_id may not be NULL

Can anyone tell me what I miss?

I think you should use the prefix even in GET mode:

def create(request):
>>   a_form = AForm(prefix="a") 
>>   b_form = BForm(prefix="b")
     if request.method == 'POST':
          a_form = AForm(request.POST, prefix="a")
          b_form  = BForm(request.POST, prefix="b")
     if a_form.is_valid() and b_form.is_valid():
          a = a_form.save()
>>        b = b_form.save(commit=False)
>>        b.a = a
>>        b.save()
          return HttpResponseRedirect('/companies/detail/{b.id}')
     return render_to_response('companies/signup.html',{'AForm':a_form , 'BForm': b_form }, context_instance=RequestContext(request))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM