Table of contents
1.
Introduction
2.
Django Modelformsets factory
3.
Creating and using Django ModelFormsets
4.
Creating Multiple forms using Django ModelFormsets
5.
Handling Multiple forms using Django Formsets
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Django ModelFormSets

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django ModelFormsets is an advanced way of handling multiple forms created using a Django model and using them to create Django model instances. In other words, Django ModelFormsets are a group of multiple forms in Django. We might want to initiate multiple forms on a single web page, all or some of which may involve multiple POST requests. For example

class Coding Ninjas StudioModel(models.Model):
    title = models.CharField(max_length = 200)
    description = models.TextField()
You can also try this code with Online Python Compiler
Run Code

 

If we want to create a Django ModelFormSet for this model, modelformset_factory() needs to be used. A Django formset is a layer of abstraction that works with multiple forms on the same page. It is best compared to a data grid.

from django.forms import formset_factory
Coding Ninjas StudioFormSet = modelformset_factory(Coding Ninjas StudioModel)
You can also try this code with Online Python Compiler
Run Code

Django Modelformsets factory

The Django modelformset_factory() method is the centrepiece of working with Django ModelFormSets. The modelformset_factory method may have nineteen arguments, nine of which are identical to standard Django FormSets, and the remaining ones are specific to Django ModelFormSets. The following snippet shows all the names and default values for each argument in the modelormset_factory method:

modelformset_factory(model, queryset=model.objects.all(),
                    form=ModelForm,fields=None, exclude=None,
                  formset=BaseModelFormSet, extra=1, can_order=False, can_delete=False,
                  max_num=None, min_num=None, validate_max=False, validate_min=False,
                  widgets=None, localized_fields=None,labels=None,
                 help_texts=None, error_messages=None,
                  field_classes=None,formfield_callback=None)
You can also try this code with Online Python Compiler
Run Code

 

In the above snippet, we can see that modelformset_factory() takes a lot of arguments. Let's see them in detail.

Argument

Description

model It is used to define the model class on which we need to create a ModelFormSet.
queryset Define the queryset to create a formset. model.objects.all() as default value.
fields Define the ModelForm fields to include as a part of a model to create the Django ModelFormSets.
exclude Define the ModelForm fields to omit as a part of a model to create the Django ModelFormSets.
widgets Define overriding widgets for a model form to create the ModelFormset.
localize_fields Define ModelForm fields to localize (i.e., to support multiple languages) to create the ModelFormset.
labels Define overriding the label for a model form to create the ModelFormSet.
help_text Defines overriding help text for a model form to create the ModelFormSet.
error_messages Define overriding error messages for a model form to create the ModelFormSet.
field_classes Defines overriding field classes for a model form to create the ModelFormSet.
formsetfield_callback Define a method to execute before creating a form field from the model field. 

Although the only required argument for Django ModelFormSets is the model field in the modelformset_factory method. This field defines the Django model class on which we will create Django ModelFormSets.

Read this, Introduction to JQuery

Creating and using Django ModelFormsets

For this article, let us consider a project named codingninjas having an application called Coding Ninjas Studio.

Refer to the below articles to check how to create a project and an application in Django.

Now, let's create a new file models.py in our Django application. We will make all the required Django models in this file.

from django.db import models
 
# Declaring a new model
class Coding Ninjas StudioModel(models.Model):
 
    # Fields in the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
    # Using __str__() method
    def __str__(self):
            return self.title
You can also try this code with Online Python Compiler
Run Code

 

In the above code, we declared a new model Coding Ninjas StudioModel. This model has two fields title and description. In the model, we also added the __str__() method to change the display name of the model instance.

Now, we will create a simple Django FormSet of this form. So, let's move to views.py and add the following code.

from django.shortcuts import render
from .forms import Coding Ninjas StudioModel
from django.forms import formset_factory
 
def formset_view(request):
    context ={}
 
    # Creating a new Formset
    Coding Ninjas StudioFormSet = modelformset_factory(Coding Ninjas StudioModel)
    formset = Coding Ninjas StudioFormSet()
      
    # Adding the formset to context dictionary
    context['formset']= formset
    return render(request, "forms.html", context)
You can also try this code with Online Python Compiler
Run Code

 

In the above code, we created a simple Django formset named formset_view. Now, Let’s create forms.html file to render the formset through Django Template. Add the following code in template/forms.html.

<form method="POST" enctype="multipart/form-data">
            // Cross site sctripting tag
    {% csrf_token %}
    {{ formset.as_p }}
    <input type="submit" value="Submit Data">
</form>
You can also try this code with Online Python Compiler
Run Code

 

After creating the Django Template for Formset, let's add the Url in our Coding Ninjas Studio/urls.py file.

from django.urls import path
from .views import formset_view


urlpatterns = [
    path('/forms', forms, name=formset_view),
]
You can also try this code with Online Python Compiler
Run Code

 

Now, let's see the output by visiting https://localhost:8000/forms. 

Output

Creating Multiple forms using Django ModelFormsets

Django Formsets allows us to handle multiple instances of one form. We can create various forms easily with the help of extra attribute of Django Formsets. In Coding Ninjas Studio/views.py.

from django.shortcuts import render
from .forms import Coding Ninjas StudioModel
from django.forms import formset_factory
 
def formset_view(request):
    context ={}
 
    # Creating Formset and its three instances
    Coding Ninjas StudioFormSet = modelformset_factory(Coding Ninjas StudioModel, extra = 3)
    formset = Coding Ninjas StudioFormSet()
 
    # Add the formset to context dictionary
    context['formset']= formset
    return render(request, "forms.html", context)
You can also try this code with Online Python Compiler
Run Code

 

The keyword extra makes multiple copies of the same form in the above code. For creating three forms, we can set extra= 3. Now, let's visit https://localhost:8000/forms to see the changes.

Output

Handling Multiple forms using Django Formsets

Creating and using a form is easier than handling the entered data into those fields at the back end. This section will try to demonstrate how we can use the data of the Django ModelFormSets. For handling data Django ModelFromSets requires an extra argument {{ formset.management_data }}. We will add this extra argument in template/forms.html file.

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
            {{ formset.management_data }}
    {{ formset.as_p }}
    <input type="submit" value="Submit Data">
</form>
You can also try this code with Online Python Compiler
Run Code

 

Now to check how and what kind of data is being rendered. We can edit formset_view to print the data. In Coding Ninjas Studio/view.py.

from django.shortcuts import render
from .forms import Coding Ninjas StudioModel
from django.forms import formset_factory
 
def formset_view(request):
    context ={}
 
    # Creating Formset and its 3 instances
    Coding Ninjas StudioFormSet = modelformset_factory(Coding Ninjas StudioModel, extra = 3)
    formset = Coding Ninjas StudioFormSet()
 
           # print formset data if it is valid
           if formset.is_valid():
                 for form in formset:
                     print(form.cleaned_data)
 
    # Add the formset to context dictionary
    context['formset']= formset
    return render(request, "forms.html", context)
You can also try this code with Online Python Compiler
Run Code

 

With the above code, we have successfully learned how to handle data in Django ModelformSets.

FAQs

  1. What is the difference between formset_factory and modelformset_factory?
    formset_factory lets us render a bunch of forms together, but these forms are NOT necessarily related to the same database models, while modelformset_factory lets us edit/create a bunch of Django model objects together.
     
  2. What is the role of fields in modelformset_factory()?
    This field defines the model form fields to be included in the model to create the Django Modelformset.

Key Takeaways

In this article, we learned about Django ModelFormsets. We created and used Django Modelformsets. We also multiple forms using Django Modelformsets. Finally, we learned to handle and manage data throughout multiple Django Modelformsets.

Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass