2 forms in one html page django code example
Example 1: working with multiple html forms django
# views.py
def _get_form(request, formcls, prefix):
data = request.POST if prefix in request.POST else None
return formcls(data, prefix=prefix)
class MyView(TemplateView):
template_name = 'mytemplate.html'
def get(self, request, *args, **kwargs):
return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})
def post(self, request, *args, **kwargs):
aform = _get_form(request, AForm, 'aform_pre')
bform = _get_form(request, BForm, 'bform_pre')
if aform.is_bound and aform.is_valid():
# Process aform and render response
elif bform.is_bound and bform.is_valid():
# Process bform and render response
return self.render_to_response({'aform': aform, 'bform': bform})
# mytemplate.html
<form action="" method="post">
{% csrf_token %}
{{ aform.as_p }}
<input type="submit" name="{{aform.prefix}}" value="Submit" />
{{ bform.as_p }}
<input type="submit" name="{{bform.prefix}}" value="Submit" />
</form>
Example 2: how to submit two forms in django
if request.method == 'POST':
form1 = Form1( request.POST,prefix="form1")
form2 = Form2( request.POST,prefix="form2")
if form1.is_valid():
# save them
# context['form1_message'] = 'Form1 saved'
else:
#save them into context
context['form1']= form1
if form2.is_valid():
# save them
# context['form2_message'] = 'Form2 saved'
else:
#save them into context
context['form2']= form2
if form1.is_valid() and form2.is_valid():
#that's mean both form is valid and saved successfully
return redirect('page')
else:
return render('/page', context)
else:
form1 = Form1(prefix="form1")
form2 = Form2(prefix="form2")