Создайте представление, которое будет условно проверять, какой шаг процесса в настоящее время отправляется, затем проверяет форму, а также выбирает, какая форма будет следующей.
forms.py
class BaseForm(forms.Form)
# All our forms will have a hidden field identifying them as either A, B or C
type = forms.HiddenField(...)
class formA(BaseForm)
# These are the rest of your attibutes (such as 'name' etc.)
a_1 = forms.TextField(...)
a_2 = forms.TextField(...)
class formB(BaseForm)
b_1 = forms.TextField(...)
b_2 = forms.TextField(...)
....
class formC(BaseForm)
c_1 = forms.TextField(...)
c_1 = forms.TextField(...)
views.py
Это представление может быть вызвано из URL / form-wizard / и выяснит, какую из трех форм оно получает и какую форму оно предоставит для следующего шага. Когда все данные собраны, можно выполнить некоторую переадресацию или дальнейшую логику.
def form_wizard(self, request):
next_form = None
curr_form = None
if request.method=='POST':
# Find out if we have received a form in our chain
type = request.POST.get("type", None)
if type == 'a':
# We are now processing Form A
curr_form = FormA(request.POST)
if curr_form.is_valid():
# Do a check on the attributes (i.e. name==None)
if curr_form.cleaned_data.get('a_1',None):
next_form = FormB()
# Now set the value of type to 'b' for the next form
next_form.fields['type'].initial = 'b'
else:
next_form = FormC()
next_form.fields['type'].initial = 'c'
elif type == 'b':
# Processing B
curr_form = FormB(request.POST)
if form.is_valid():
# Do something with this form
....
next_form = FormC()
next_form.fields['type'].initial = 'c'
elif type == 'c':
# Processing C
curr_form = FormC(request.POST)
if curr_form.is_valid():
# Last form in chain; either redirect or do something else
return HttpResponseRedirect(...)
else:
# First visit to the wizard, give them the first form
curr_form = FormA()
curr_form.fields['type'].initial = 'b'
return .... {'form':curr_form}
Наконец, в вашем шаблоне:
template.html
Будет отображаться любая форма, которую мы передали шаблону (A, B или C)
...
<form action="/form-wizard/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
...
Единственная другая проблема, с которой вы можете столкнуться, это как сохранить данные из первой формы до тех пор, пока вы успешно не заполните третью форму. Эту проблему можно легко решить, сохранив любые допустимые поля формы из первой формы в сеансе пользователя, используя встроенную в Django обработку сеанса:
https://docs.djangoproject.com/en/dev/topics/http/sessions/#examples