你應該:
的Python:
from django import forms
class FormA(forms.ModelForm):
[...]
class FormB(forms.ModelForm):
[...]
HTML:
<form method="post" action="/path/to/view/">
{% csrf_token %}
{{ form_a }}
{{ form_b }}
<input type="submit" value="Submit Form" />
</form>
然後,當你正在處理您的表格,只需處理它們,並確保您要求兩者都有效,才能在成功案例中實際完成視圖。
from django.db import transaction
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from myapp.forms import FormA, FormB
@transaction.commit_on_success
def present_forms_to_user(request):
if request.method == 'POST':
form_a = FormA(request.POST)
form_b = FormB(request.POST)
if form_a.is_valid() and form_b.is_valid():
# processing code
return HttpResponseRedirect('/path/to/thank/you/page/')
else:
form_a = FormA()
form_b = FormB()
return TemplateResponse(request, 'templates/eggs.html', {
'form_a': form_a,
'form_b': form_b,
})
作爲一個免責聲明,請記住,這是一個基本的示例存根,並不是要盲目複製。你的最終用例可能會略有不同,這很好。
感謝您的回答。值得注意的是formset的'prefix'參數(https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-more-than-one-formset-in-a-view) 。 – orokusaki