Django – Handling multiple forms in single view

PythonServer Side ProgrammingProgramming

We sometimes need to handle multiple forms in a single function or view. In this article, we will see how to write a function which will handle two forms at the same time and in same view. It is handy in many cases; we will handle more than two forms too.

Create a Django project and an app, I named the project "multipleFormHandle" and the app as "formhandlingapp".

Do some basic stuff like including app in INSTALLED_APPS and include app's url in project's url.

Now create in app and a "templates" folder in the app directory. Add home.html in templates.

Install the multi-form_view library −

pip install multi_form_view


Now in of app −

from django.urls import path,include
from . import views
urlpatterns = [

Here, we setup views and use our viewset as view. We are going to use viewset here.


from django.db import models

# Create your models here.

class StudentData(models.Model):

class TeachertData(models.Model):

We created two models because we are going to save forms data in models.


from django import forms
from .models import TeachertData,StudentData

class StudentForm(forms.ModelForm):
   class Meta:

class TeacherForm(forms.ModelForm):
   class Meta:

Here, we created model forms which we will render on the frontend from our view.

In home.html

<!DOCTYPE html>
      <form method="post" enctype="multipart/form-data">
         {% csrf_token %}

         //accessing form 1 from view
         {{ forms.teacher_form.as_p }}
         //accessing form 2 from view
         {{ forms.student_form.as_p }}
         <input type="submit" value="submit"/>

It is our frontend where we render two Django forms under a single form element and with a single submit button.

I will not add style, because here we are learning the concept and the way to do that.


from django.shortcuts import render
from .forms import StudentForm,TeacherForm
from django.views.generic.list import ListView
from django.urls import reverse

from multi_form_view import MultiModelFormView
# Create your views here.
class SchoolData(MultiModelFormView):
   form_classes = {
      'student_form' : StudentForm,
      'teacher_form' : TeacherForm,
   template_name = 'home.html'
   def get_success_url(self):
      return reverse('home')
   def forms_valid(self, forms):
      student = forms['student_form'].save(commit=False)
      return super(SchoolData, self).forms_valid(forms)

Here we created a viewset, we define two forms to render one is student form and the other is teacher form. We defined the HTML which we have to render. We define what to do when a form is submitted under get_success_url. In form_valid, we save the form data and verify if both the forms are right or not.


Published on 26-Aug-2021 11:49:25