[英]Multiple ModelForm in Django
我在models.py中有類似的東西
class A(models.Model):
name = CharField(max_length=150)
class B(models.Model):
a= ForeignKey(A)
name = CharField(max_length=150)
我在views.py中為兩者創建了modelform
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))
我得到這個錯誤
Exception Value: mysite_b.a_id may not be NULL
誰能告訴我我想念什么?
我認為即使在GET模式下,您也應該使用前綴:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.