我对django中的表单有疑问。我有两种提交形式。逻辑是:
- 如果在form1中,OIB不会在数据库中插入它,并插入form2。
- 如果在form1中OIB存在于数据库传递中,并插入第二个表单(form2),但要求数据库获取来自form1的OIB相关的id。
醇>
以下是我的views.py
的示例@login_required
@csrf_protect def NewOutgoingInvoice(请求): template =" novi_izlazni_racun.html" user_pk = request.user.id org_name = OrganizationInfo.objects.filter(id = user_pk).values(' name')[0] org_id = request.user.organization_id
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已存在,则表单不会提交。