django two forms on one page code example
Example 1: multiple form in one class djanog
class MultipleFormsDemoView(MultiFormsView):
template_name = "pages/cbv_multiple_forms.html"
form_classes = {'contact': ContactForm,
'subscription': SubscriptionForm,
}
success_urls = {
'contact': reverse_lazy('contact-form-redirect'),
'subscription': reverse_lazy('submission-form-redirect'),
}
def contact_form_valid(self, form):
'contact form processing goes in here'
def subscription_form_valid(self, form):
'subscription form processing goes in here'
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")