Formsets let you handle many similar forms on one page easily. They help you save or update multiple records at once.
0
0
Formsets for multiple forms in Django
Introduction
You want users to add several items in one go, like multiple addresses or contacts.
You need to edit a list of related objects together, such as updating several books by an author.
You want to validate many forms with the same structure in one submission.
You want to allow users to add or remove forms dynamically on a page.
Syntax
Django
from django.forms import formset_factory MyFormSet = formset_factory(MyForm, extra=3) formset = MyFormSet(request.POST or None)
formset_factory creates a formset class from a single form class.
The extra parameter controls how many empty forms show by default.
Examples
This creates a formset class that will show 2 blank forms for new data.
Django
from django.forms import formset_factory # Create a formset with 2 extra empty forms MyFormSet = formset_factory(MyForm, extra=2)
Process submitted formset data and print cleaned data from each form.
Django
formset = MyFormSet(request.POST or None) if formset.is_valid(): for form in formset: print(form.cleaned_data)
Use
modelformset_factory to create formsets tied to database models.Django
from django.forms import modelformset_factory # For model forms, use modelformset_factory BookFormSet = modelformset_factory(Book, fields=['title', 'author'], extra=1)
Sample Program
This example creates a formset for two contact forms. It simulates submitting data for two contacts and prints their names and emails after validation.
Django
from django import forms from django.forms import formset_factory class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() ContactFormSet = formset_factory(ContactForm, extra=2) # Simulate POST data for two contacts post_data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '1000', 'form-0-name': 'Alice', 'form-0-email': 'alice@example.com', 'form-1-name': 'Bob', 'form-1-email': 'bob@example.com', } formset = ContactFormSet(post_data) if formset.is_valid(): for i, form in enumerate(formset): print(f"Contact {i+1}:") print(f" Name: {form.cleaned_data['name']}") print(f" Email: {form.cleaned_data['email']}") else: print("Formset is not valid")
OutputSuccess
Important Notes
Always include management form data like TOTAL_FORMS and INITIAL_FORMS when processing formsets.
Use modelformset_factory if you want to work directly with database models.
Formsets help keep your code clean when handling multiple forms of the same kind.
Summary
Formsets let you manage many similar forms together easily.
Use formset_factory for regular forms and modelformset_factory for model forms.
Remember to handle management form data when processing formsets.