How to use Django ModelFormSets

Django is an open-source high-level Python web framework that encourages rapid development and clean, pragmatic design.

What is ModelFormSets?

In Django, ModelFormsets is an advanced way to handle multiple forms created with a model. ModelFormSets uses the model to create model instances.

Just as standard Django forms can be grouped together as a set in a Django FormSet, Django model forms can be grouped into a ModelFormSet. ModelFormSet also has a lot of similarities with the standard FormSet.

ModelFormSet can be used to initialize multiple forms, involving POST requests on some or all of them, on a single page.

Code

The example below demonstrates how ModelFormSet can be used.

Installation

pip install pipenv
pipenv shell
pipenv install django

Then:

django-admin startproject DjangoFormset ./
python manage.py startapp codebase
python manage.py migrate
python manage.py runserver

Once the settings have been initialized, the following changes should be made.

Go to settings.py and enter the following:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'codebase'
]

In the codebase app folder, the code below is added to the model.py file.

from django.db import models
# adding the model
class ModelFormSetModel(models.Model):
name = models.CharField(max_length = 200)
email = models.CharField(max_length=200)
department = models.TextField()
# the name of the model that will be showing in the admin panel
class Meta:
verbose_name_plural = 'data'
#so it will use emaill to reference a particular data
def __str__(self):
return self.email

Views.py

This is the main part that focuses on ModelFormSet and explains how it is implemented.

In order to use ModelFormSet, Django makes use of modelformset_factory.

For example:

from .models import ModelFormsetModel
from django.forms import modelformset_factory


DjangoFormset = modelformset_factory(ModelFormsetModel, fields = '__all__')

This is the main code for views.py:

from django.shortcuts import render
#importing the model
from .models import ModelFormSetModel
# importing django modelformset_factory used for modelformset
from django.forms import modelformset_factory
def home(request):
#displaying the neccessary fields needed to be displayed on the frontend
DjangoFormSet = modelformset_factory(ModelFormSetModel, fields =['name', 'email','department'])
# refrencing the DjangoFormset as a method
formset = DjangoFormSet()
# Add the formset to context dictionary
context = {
'formset':formset
}
return render(request, "app/home.html", context)

In the codebase app, create a folder and name it templates. Inside the templates folder, create another folder and name it app, and inside the app folder, create a home.html file.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django ModelFormSets</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<!-- csrf token -->
{% csrf_token %}
<!-- displaying the form from the backend -->
{{ formset.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>

In the urls.py file in the DjangoFormset folder, add the following:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# including the codebase urls.py file
path('', include('codebase.urls'))
]

Then, in the codebase folder, create a file and name it urls.py.

from django.urls import path
from .views import home
urlpatterns = [
path('', home, name='home'),
]

Testing

Run the following commands:

python manage.py makemigrations

python manage.py migrate

After this, run:

python manage.py runserver

Then, go to:

http://127.0.0.1:8000

Free Resources