The Wayback Machine - https://web.archive.org/web/20241126194807/https://www.geeksforgeeks.org/django-formsets/
Open In App

Django Formsets

Last Updated : 09 Jan, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Formsets in a Django is an advanced way of handling multiple forms on a single webpage. In other words, Formsets are a group of forms in Django. One might want to initialize multiple forms on a single page all of which may involve multiple POST requests, for example

from django import forms
class GeeksForm(forms.Form):
    title = forms.CharField()
    pub_date = forms.DateField()

Now one might want to permit the user to create articles at once, so if thought in a conventional manner one uses multiple forms and different names for each form to handle data on a single page but this would complicate the code as well as functionality. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.
Now to create a formset of this GeeksForm,

from django.forms import formset_factory
GeeksFormSet = formset_factory(GeeksForm)

Creating and using Django Formsets

Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how,
In your forms.py Enter the following,




from django import forms
  
# create a form
class GeeksForm(forms.Form):
    title = forms.CharField()
    description = forms.CharField()


Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as
Syntax :

Field_name = forms.FieldType(attributes)

Now to create a simple formset of this form, move to views.py and create a formset_view as below.




from django.shortcuts import render
  
# relative import of forms
from .forms import GeeksForm
  
# importing formset_factory
from django.forms import formset_factory
  
def formset_view(request):
    context ={}
  
    # creating a formset
    GeeksFormSet = formset_factory(GeeksForm)
    formset = GeeksFormSet()
      
    # Add the formset to context dictionary
    context['formset']= formset
    return render(request, "home.html", context)


To render the formset through HTML, create a html file “home.html”. Now let’s edit templates > home.html




<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ formset.as_p }}
    <input type="submit" value="Submit">
</form>


All set to check if our formset is working or not let’s visit http://localhost:8000/.
django-formsets.
Our formset is working completely. Let’s learn how to modify this formset to use extra features of this formset.

How to create Multiple forms using Django Formsets

Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra attribute of Django Formsets. In geeks/views.py,




from django.shortcuts import render
  
# relative import of forms
from .forms import GeeksForm
  
# importing formset_factory
from django.forms import formset_factory
  
def formset_view(request):
    context ={}
  
    # creating a formset and 5 instances of GeeksForm
    GeeksFormSet = formset_factory(GeeksForm, extra = 5)
    formset = GeeksFormSet()
      
    # Add the formset to context dictionary
    context['formset']= formset
    return render(request, "home.html", context)


The keyword argument extra makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others. Visit http://localhost:8000/ to check if 5 forms are created.
django-formsets-multiple-forms

Handling Multiple forms using Django Formsets

Creating a form is much easier than handling the data entered into those fields at the back end. Let’s try to demonstrate how one can easily use the data of a formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, visit Understanding the ManagementForm.
In templates/home.html,




<form method="POST" enctype="multipart/form-data">
      
    <!-- Management data of formset -->
    {{ formset.management_data }}
  
    <!-- Security token -->
    {% csrf_token %}
  
    <!-- Using the formset -->
    {{ formset.as_p }}
      
    <input type="submit" value="Submit">
</form>


Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py,




from django.shortcuts import render
  
# relative import of forms
from .forms import GeeksForm
  
# importing formset_factory
from django.forms import formset_factory
  
def formset_view(request):
    context ={}
  
    # creating a formset and 5 instances of GeeksForm
    GeeksFormSet = formset_factory(GeeksForm, extra = 3)
    formset = GeeksFormSet(request.POST or None)
      
    # 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, "home.html", context)


Now let’s try to enter data in the formset through http://localhost:8000/
enter-formset-data-django-formsets
Hit submit and data will be display in command line where server is running. One can use this data in any manner conveniently now.
django-formsets-use-data1
Formset is advanced stuff which can be used to resolve a number of problems but should be used with correct syntax and field validations otherwise conflicts and errors will disrupt the normal functioning. To know more about Formsets, Visit Official Documentation for Formsets.



Previous Article
Next Article

Similar Reads

Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read
How to Fix Django "ImportError: Cannot Import Name 'six' from 'django.utils'"?
After Django 3.0, django.utils.six was removed. The "ImportError: Cannot Import Name 'six' from 'django.utils'" error occurs because of the dependency issue. This happens because when the project tries to use something that’s no longer available. Don’t worry—it’s easy to fix. We’ll explain why this error happens and give you simple steps to solve i
3 min read
Handling Ajax request in Django
Introduction This tutorial explains how to carry out an ajax request in the Django web framework. We will create a simple post-liking app as a part of the example. Glossary Project InitializationCreate modelsCreate viewsWrite URLsCarry out a request with Jquery Ajax.Register models to admin and add some posts. Implementation: 1. Initiate the Django
4 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Sites like Hot Frameworks assess the popularity of a
3 min read
now - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of programming such as variables,
2 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the different packages available on tour booking servi
4 min read
Python | Django Admin Interface
In this article, we delve into the capabilities and advantages of the Django Admin Interface, exploring how its customizable features and streamlined workflows empower developers to effortlessly administer their projects, from data management to user interactions. Prerequisites: django-introduction-and-installation | django-introduction-set-2-creat
4 min read
Python Django | Google authentication and Fetching mails from scratch
Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We'll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these libraries as there was no proper documentation av
12 min read
Built-in Error Views in Django
Whenever one tries to visit a link that doesn't exist on a website, it gives a 404 Error, that this page is not found. Similarly, there are more error codes such as 500, 403, etc. Django has some default functions to for handle HTTP errors. Let's explore them one-by-one. Built-in Error Views in Django - 404 view (page not found) - Normally this vie
3 min read
How to add RSS Feed and Sitemap to Django project?
This article is in continuation of Blog CMS Project in Django. Check this out here - Building Blog CMS (Content Management System) with Django RSS (Really Simple Syndication) Feed RSS (Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. These feeds ca
3 min read
Intermediate fields in Django | Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship exists between two models A and B, when one instance of A is related to multiple instances of B, and vice versa. For example - In a shop management system, an Item and a Customer share a many-to-many relationship, as one customer can buy multiple items, a
2 min read
Django - Dealing with warnings
Prerequisite : Django - Creating project Django is a great framework which provides you a lot of pre-defined services and workflow so that one can work flawlessly. Django apps are designed to make your code clean and reusable. Django works on the concept of DRY which means Don't Repeat Yourself. After creating project , your directory should look l
2 min read
Django - Creating Apps | Set - 1
Prerequisites: Django – Dealing with warnings Why do we need apps? In Django Set 2 (Creating a Project), we saw how we can display text in our browser using Django but that is not the best and pythonic way. Django recommends using the project-app relationship to build Django projects. Any website contains different sections. For example, Geeksforge
1 min read
Django - Creating apps | Set - 2
In the previous article, we discussed why apps are important in Django project management? What are the benefits of using Django apps? In this article, we will discuss what are we going to build and how do apps play a vital role in Django projects? Project outline - We will build a localhost e-commerce mobile phone website which can show us details
2 min read
Django Models | Set - 1
Prerequisites : Django Creating apps Models - According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models
2 min read
Django Models | Set - 2
Model Fields - Model fields define the datatype which will be stored in the provided variable. To store price, the integer type is more suitable. To store height, length etc. float/decimal type is more suitable. To store title or heading, it is better to provide character limit. For writing an article, it is better to have a textbox with no charact
2 min read
Python | Django News App
Django is a high-level framework which is written in Python which allows us to create server-side web applications. In this article, we will see how to create a News application using Django. We will be using News Api and fetch all the headline news from the api. Read more about the api here news api.Do the Following steps in command prompt or term
2 min read
Django Migrations | Python
Prerequisite: Django Models No such table? - The class defined in product/models.py is the mere idea of what our database is going to look like but it didn't create any table in the database. We can assume class Phone as conceptual schema. Before the creation of any table, if we try to access the table before creation, it will throw an error like t
2 min read
Python | Relational fields in Django models
Prerequisite: Django models Django models represent real-world entities, and it is rarely the case that real-world entities are entirely independent of each other. Hence Django supports relational databases and allows us to establish relations between different models. There are three types of relational fields which Django supports: many-to-one, m
4 min read
Django URL patterns | Python
Prerequisites: Views in Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration) Let the project name be myProject. The Python module to
2 min read
Django Templates | Set - 1
There are two types of web pages - Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don't change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages whose content are generated dynamically i.e. They
2 min read
Django Templates | Set - 2
Prerequisite: Django Templates | Set-1, Views In Django. Navigate to brand/views.py and add following code to brand/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def ViewDemo(request): return HttpResponse("<h1>Hello World. Welcome to views.py.</h1>") def homepage(re
2 min read
Weather app using Django | Python
In this tutorial, we will learn how to create a Weather app that uses Django as backend. Django provides a Python Web framework based web framework that allows rapid development and clean, pragmatic design. Basic Setup - Change directory to weather – cd weather Start the server - python manage.py runserver To check whether the server is running or
2 min read
When to Use Django? Comparison with other Development Stacks
Prerequisite - Django Introduction and Installation When to Use Django and Why? After getting to know the basics of Python, one should know when to use Django and why? Django is a high-level python based web framework which allows you to quickly create web applications without all of the installation or dependency problems that you normally will fi
4 min read
Django Project MVT Structure
Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. MVT Structure has the following three parts - Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is repr
2 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To initiate a project of Django on Your PC, open Terminal
2 min read
Complete Django History | Python
Prerequisite - When to Use Django ? Comparison with other Development Stacks Django was design and developed by Lawrence journal world in 2003 and publicly released under BSD license in July 2005. Currently, DSF (Django Software Foundation) maintains its development and release cycle. Django was released on 21, July 2005. Its current stable version
2 min read
Practice Tags :
three90RightbarBannerImg