Python Django提交两份表格
我对django的表单有疑问。我有两份表格要提交。逻辑是: 如果在表格1中OIB在数据库中不存在,请插入它,然后插入表格2。 若表单1中的OIB存在于数据库pass中,则插入第二个表单form2,但要求数据库从表单1中获取与OIB相关的id。 下面是my views.py的示例 views.py @保护 def New OutgoingInvoiceRequest: template=novi_izlazni_racun.html user\u pk=request.user.id org\u name=OrganizationInfo.objects.filterid=user\u pk.values'name'[0] org\u id=request.user.organization\u idPython Django提交两份表格,python,django,forms,Python,Django,Forms,我对django的表单有疑问。我有两份表格要提交。逻辑是: 如果在表格1中OIB在数据库中不存在,请插入它,然后插入表格2。 若表单1中的OIB存在于数据库pass中,则插入第二个表单form2,但要求数据库从表单1中获取与OIB相关的id。 下面是my views.py的示例 views.py @保护 def New OutgoingInvoiceRequest: template=novi_izlazni_racun.html user\u pk=request.user.id org\u
if request.method == 'POST':
form1 = InsertNewCustomer(request.POST)
form2 = Outdrew(request.POST, request.user)
if form1.is_valid() and form2.is_valid():
# First form
a_1, created = OrganizationInfo.objects.get_or_create(**form1.cleaned_data)
if a_1:
# Seconf Form
a_1.save()
b = form2.save(commit=False)
b.user_id = request.user
b.organization_id = org_id
b.customer_id = a_1
b.save()
return HttpResponseRedirect('/novi_izlazni_racuni/')
if created:
# Seconf Form
b = form2.save(commit=False)
b.user_id = request.user
b.organization_id = org_id
b.customer_id = OrganizationInfo.objects.get(oib=form1.cleaned_data['oib'])
b.save()
return HttpResponseRedirect('/novi_izlazni_racuni/')
else:
form1 = InsertNewCustomer()
form2 = Outdrew()
variables = RequestContext(request, dict(name=org_name, form1=form1, form2=form2))
return render_to_response(template, variables)
此视图仅在form1中为新oib且正常工作时有效,两个表单都插入到数据库中,但如果oib已存在,表单将不会提交。第一个if将始终根据执行。因此,没有必要使用if
当form1 OIB存在时,您的elif将不会如您所愿执行。@cark_kralj看起来您没有使用在a=form1.savecommit=False中创建的?那么这意味着什么呢?我已经删除了a=form1.savecommit=False。和更新的代码。@cark_kralj我也修改了我的答案。
if request.method == 'POST':
form1 = InsertNewCustomer(request.POST)
form2 = Outdrew(request.POST, request.user)
if form1.is_valid() and form2.is_valid():
# First form
a_1, created = OrganizationInfo.objects.get_or_create(**form1.cleaned_data)
if a_1:
# Seconf Form
a_1.save()
b = form2.save(commit=False)
b.user_id = request.user
b.organization_id = org_id
b.customer_id = a_1
b.save()
return HttpResponseRedirect('/novi_izlazni_racuni/')
if created:
# Seconf Form
b = form2.save(commit=False)
b.user_id = request.user
b.organization_id = org_id
b.customer_id = OrganizationInfo.objects.get(oib=form1.cleaned_data['oib'])
b.save()
return HttpResponseRedirect('/novi_izlazni_racuni/')
else:
form1 = InsertNewCustomer()
form2 = Outdrew()
variables = RequestContext(request, dict(name=org_name, form1=form1, form2=form2))
return render_to_response(template, variables)