1if request.method == 'POST':
2 form1 = Form1( request.POST,prefix="form1")
3 form2 = Form2( request.POST,prefix="form2")
4
5 if form1.is_valid():
6 # save them
7
8 # context['form1_message'] = 'Form1 saved'
9 else:
10 #save them into context
11 context['form1']= form1
12
13 if form2.is_valid():
14 # save them
15 # context['form2_message'] = 'Form2 saved'
16 else:
17 #save them into context
18 context['form2']= form2
19
20 if form1.is_valid() and form2.is_valid():
21 #that's mean both form is valid and saved successfully
22 return redirect('page')
23 else:
24 return render('/page', context)
25
26
27else:
28 form1 = Form1(prefix="form1")
29 form2 = Form2(prefix="form2")
30
1# views.py
2def _get_form(request, formcls, prefix):
3 data = request.POST if prefix in request.POST else None
4 return formcls(data, prefix=prefix)
5
6class MyView(TemplateView):
7 template_name = 'mytemplate.html'
8
9 def get(self, request, *args, **kwargs):
10 return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})
11
12 def post(self, request, *args, **kwargs):
13 aform = _get_form(request, AForm, 'aform_pre')
14 bform = _get_form(request, BForm, 'bform_pre')
15 if aform.is_bound and aform.is_valid():
16 # Process aform and render response
17 elif bform.is_bound and bform.is_valid():
18 # Process bform and render response
19 return self.render_to_response({'aform': aform, 'bform': bform})
20
21# mytemplate.html
22<form action="" method="post">
23 {% csrf_token %}
24 {{ aform.as_p }}
25 <input type="submit" name="{{aform.prefix}}" value="Submit" />
26 {{ bform.as_p }}
27 <input type="submit" name="{{bform.prefix}}" value="Submit" />
28</form>
29