Django has no built-in nested formset. You build one by attaching a child inline formset to every form of a parent inline formset in add_fields(), giving each child formset a unique prefix taken from its parent form, then overriding is_valid() and save() so the inner level is validated with its parents and saved after them.
Tested with Django 5.2.19 and Python 3.12 on 17 November 2026: every example below was run with Django's test client, creating, editing and deleting rows at both levels and checking the validation errors. Still on an older release? Our guide to upgrading Django 4.2 to 5.2 covers the safe path.
Key takeaways
- A nested formset is an inline formset whose every form contains its own child inline formset (for example Parent -> Child -> Address).
- Django ships
formset_factory,modelformset_factoryandinlineformset_factory, but not a nested formset. You wire it by hand or use thedjango-nested-formsetpackage. - The whole trick is overriding
BaseInlineFormSet.add_fields()to hang a child formset on each form with a uniqueprefix. - Override
is_valid()andsave()so the nested level is validated and saved too, and skip rows marked for deletion. - Save parents before children: the parent formset must create primary keys before the nested formset can set its foreign key.
- Override the child form's
has_changed()so a blank parent row with filled-in children fails validation instead of crashing on save. - The most common bug is a missing nested
management_formor a prefix collision. Django reports it as "ManagementForm data is missing or has been tampered with" innon_form_errors().
New to formsets? Read Django model formsets in detail first: nested formsets build directly on that foundation, and a quick refresher on Django forms basics helps too.
What is a nested formset in Django?
A formset manages multiple copies of the same form in one view: it tracks how many forms existed initially, which were changed, and which should be deleted. A model formset does the same for instances of a model, and an inline formset (inlineformset_factory) handles a set of child objects that share one foreign key, for example all children of a parent.
A nested formset goes one level deeper: each form inside an inline formset carries its own inline formset. Think Parent -> Child -> Address, or Order -> LineItem -> Adjustment. Django does not provide this out of the box, so you assemble it from inline formsets.
Consider these models (every ForeignKey needs an explicit on_delete):
# models.py
from django.db import models
class Parent(models.Model):
name = models.CharField(max_length=255)
class Child(models.Model):
parent = models.ForeignKey(
Parent, on_delete=models.CASCADE, related_name="children"
)
name = models.CharField(max_length=255)
class Address(models.Model):
child = models.ForeignKey(
Child, on_delete=models.CASCADE, related_name="addresses"
)
country = models.CharField(max_length=255)
state = models.CharField(max_length=255)
address = models.CharField(max_length=255)Formset, model formset, inline formset or nested formset?
Pick the lightest tool that fits. Only reach for a nested formset when you genuinely need to edit two levels of children on one page.
| Tool | What it manages | Foreign-key aware? | Built into Django? |
|---|---|---|---|
formset_factory |
N copies of a plain Form |
No | Yes |
modelformset_factory |
N rows of a single model | No | Yes |
inlineformset_factory |
child rows tied to one parent via FK | Yes, one level | Yes |
| Nested formset | children that each own grandchildren | Yes, two levels | No, you wire it |
If a single inline formset covers your screen, stop there. Nested formsets add real complexity around prefixes, validation and save order, so use them deliberately.
Step 1: Start with two inline formsets
With the models above you can edit all children of a parent on one page, and all addresses of a child on another. inlineformset_factory needs fields (or exclude); leave both out and Django raises ImproperlyConfigured:
# forms.py
from django.forms.models import inlineformset_factory
from .models import Address, Child, Parent
ChildrenFormset = inlineformset_factory(
Parent, Child, fields=["name"], extra=1, can_delete=True
)
AddressFormset = inlineformset_factory(
Child, Address, fields=["country", "state", "address"], extra=1, can_delete=True
)To add or edit every child and its addresses on a single page, each child form needs a full AddressFormset attached to it. That is the nested formset. The cleanest place to wire it up is a custom BaseInlineFormSet.
Step 2: Subclass BaseInlineFormSet
BaseInlineFormSet exposes an add_fields(form, index) hook that runs once per form in the formset. Override it to build and attach a nested formset for every parent form. Wire the subclass in through the factory's formset= argument:
# forms.py
from django.forms.models import BaseInlineFormSet, inlineformset_factory
from .models import Address, Child, Parent
AddressFormset = inlineformset_factory(
Child, Address, fields=["country", "state", "address"], extra=1, can_delete=True
)
class BaseChildrenFormset(BaseInlineFormSet):
pass
ChildrenFormset = inlineformset_factory(
Parent, Child, formset=BaseChildrenFormset, fields=["name"], extra=1, can_delete=True
)Step 3: Attach a nested formset with a unique prefix
Inside add_fields(), create an AddressFormset for the child form's instance and store it on form.nested. The critical detail is the prefix: it must be unique for every child row, or the field names and management_form of different rows collide. Building it from the child form's own prefix guarantees that: the first child's addresses use children-0-addresses, the second child's children-1-addresses, and so on.
# forms.py
class BaseChildrenFormset(BaseInlineFormSet):
def add_fields(self, form, index):
super().add_fields(form, index)
# One Address formset per child form, stored on the form. Its prefix
# starts with the child form's own prefix ("children-0"), so no two
# rows share field names or a management_form.
form.nested = AddressFormset(
instance=form.instance,
data=form.data if form.is_bound else None,
files=form.files if form.is_bound else None,
prefix=f"{form.prefix}-{AddressFormset.get_default_prefix()}",
)Two details here matter more than they look:
- Check
form.is_bound, not the formset'sself.is_bound. Django also callsadd_fields()for the formset'sempty_form, which is never bound. Withself.is_bound, the nested formset insideempty_formis bound to the POST data after a failed submit, so itsmanagement_formrenders with errors and an emptyTOTAL_FORMS, and JavaScript that clones it stops working. extra,can_deleteand similar options belong on the factory, not on the formset instance. Passingextra=1toAddressFormset(...)here raisesTypeError: BaseFormSet.__init__() got an unexpected keyword argument 'extra'. Set them once ininlineformset_factory.
Step 4: Validate the nested formsets
Calling formset.is_valid() only validates the parent (children) forms. Override is_valid() so every form.nested is validated too, and the whole submission fails if any address is invalid. Skip children marked for deletion: they are removed together with their addresses, so a half-filled address row should not block the delete.
# forms.py
class BaseChildrenFormset(BaseInlineFormSet):
# ... add_fields as above ...
def is_valid(self):
result = super().is_valid()
if self.is_bound:
for form in self.forms:
# A child marked for deletion is removed with its addresses,
# so its address rows do not need to be valid.
if not self._should_delete_form(form):
result = form.nested.is_valid() and result
return resultStep 5: Save parents before children
Order matters. The parent (children) formset must save first so each new Child gets a primary key; only then can the nested AddressFormset write a valid child_id. Saving an address for an unsaved child raises ValueError: save() prohibited to prevent data loss due to unsaved related object 'child'. Override save() to run the parent save, then save the nested formset of every row that is not marked for deletion:
# forms.py
class BaseChildrenFormset(BaseInlineFormSet):
# ... add_fields and is_valid as above ...
def save(self, commit=True):
# Saving the children first gives every new Child a primary key.
result = super().save(commit=commit)
for form in self.forms:
# Deleted children take their addresses with them (CASCADE).
if not self._should_delete_form(form):
form.nested.save(commit=commit)
return resultThe save order, step by step
| Step | Action | Why it matters |
|---|---|---|
| 1 | Validate the parent formset and every nested formset | a child is not valid if its addresses are not |
| 2 | super().save() the children formset |
every new Child gets a primary key |
| 3 | For each surviving child, call form.nested.save() |
each Address gets a real child_id |
| 4 | Skip the nested save when the row is marked for deletion | on_delete=models.CASCADE removes its addresses with it |
The view in Step 6 runs the save inside transaction.atomic(), so if an address fails to save, the children saved a moment earlier are rolled back too.
Guard against a blank child row with filled-in addresses
One case still crashes. Leave the name of the empty extra child row blank but fill in an address under it. Django treats the child row as unchanged and skips it, so the child is never saved, and saving the address then fails with the ValueError above: a server error for your user. The fix belongs on the child form: count the row as changed when its nested formset has changed. Django then validates the row and shows "This field is required." next to the name. Pass the form to the factory from Step 2:
# forms.py
from django.forms.models import ModelForm
class ChildForm(ModelForm):
def has_changed(self):
# A new child row counts as filled in when any of its addresses are,
# so a blank name next to a filled-in address is a validation error,
# not a crash at save time.
return super().has_changed() or self.nested.has_changed()
ChildrenFormset = inlineformset_factory(
Parent,
Child,
form=ChildForm,
formset=BaseChildrenFormset,
fields=["name"],
extra=1,
can_delete=True,
)Step 6: Wire it into the view
The view stays almost identical to a normal inline formset: your overridden is_valid() and save() handle the nested level. Pass request.FILES if any nested form has file uploads, and save inside transaction.atomic() so children and addresses are written all or nothing:
# views.py
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render
from . import forms, models
def manage_children(request, parent_id):
"""Edit the children of one parent, and their addresses, on one page."""
parent = get_object_or_404(models.Parent, pk=parent_id)
if request.method == "POST":
formset = forms.ChildrenFormset(request.POST, request.FILES, instance=parent)
if formset.is_valid():
# All or nothing: if saving an address fails, the children
# saved a moment earlier are rolled back too.
with transaction.atomic():
formset.save()
return redirect("parent_view", parent_id=parent.pk)
else:
formset = forms.ChildrenFormset(instance=parent)
return render(
request,
"manage_children.html",
{"parent": parent, "children_formset": formset},
)Step 7: Render every management_form in the template
Each formset level needs its own management_form. Render the parent formset's management_form, then inside the loop render each nested formset's management_form before its rows. Miss one and the submit fails quietly: since Django 3.2 a missing management form no longer raises an exception. is_valid() returns False, the page re-renders without saving, and the reason ("ManagementForm data is missing or has been tampered with") appears only in non_form_errors(), so render those at both levels:
{# manage_children.html: the formset part of the page #}
<form method="post">
{% csrf_token %}
{{ children_formset.management_form }}
{{ children_formset.non_form_errors }}
{% for child_form in children_formset %}
{{ child_form.as_p }}
{{ child_form.nested.management_form }}
{{ child_form.nested.non_form_errors }}
{% for address_form in child_form.nested %}
{{ address_form.as_p }}
{% endfor %}
{% endfor %}
<button type="submit">Save</button>
</form>If you do not need custom markup, {{ child_form.nested }} renders the nested management form and every address row in one go.
Adding rows dynamically with JavaScript? Clone the formset's empty_form, replace its __prefix__ placeholder with the next index, and increase the matching TOTAL_FORMS value. Nested formsets add a catch: for a new child cloned from children_formset.empty_form, the address formset's own empty_form carries two placeholders, children-__prefix__-addresses-__prefix__. The first is the child's index and the second the address's, so replace them separately rather than with one global replace. A small custom template tag can keep that markup tidy; see Django custom template tags and filters.
Should you use the django-nested-formset package?
The community django-nested-formset package wraps this exact pattern behind a nestedformset_factory helper. Its last release, 0.1.4, came out in March 2015 and its classifiers stop at Python 3.4, yet it passed the same tests on Django 5.2.19 as the code above. It is about 100 lines and already includes the three guards from this guide: form.is_bound, skipping rows marked for deletion, and a has_changed() that includes the nested formset. Install it with pip install django-nested-formset and import it from nested_formset:
# forms.py
from django.forms.models import inlineformset_factory
from nested_formset import nestedformset_factory
from .models import Address, Child, Parent
ChildrenFormset = nestedformset_factory(
Parent,
Child,
nested_formset=inlineformset_factory(
Child, Address, fields=["country", "state", "address"], extra=1
),
fields=["name"],
extra=1,
)It uses the same children-0-addresses prefixes as the code above, so the Step 7 template works unchanged. Watch its defaults: extra=3, can_delete=True, and every model field when you leave out fields.
- Use the package for a conventional two-level form where those defaults suit you. Pin the version and read its code once, since it has had no release since 2015.
- Build it manually (the approach above) when you need three levels, conditional nesting, custom save logic, or tight control over prefixes and error handling.
Either way the mechanics are identical: add_fields, unique prefixes, a management_form per level, and parents saved before children. Understanding the manual version makes the package easy to debug.
Common nested formset pitfalls
- Missing nested
management_form: every nested formset needs its own; the parent's is not enough. Django reports "ManagementForm data is missing or has been tampered with" innon_form_errors()and the page re-renders without saving. - Prefix collisions: reusing the same prefix across rows merges their POST data; always build the prefix from
form.prefix. - Saving children before parents: raises
ValueError: save() prohibited to prevent data loss due to unsaved related object. Save the parent formset first. - A blank parent row with filled-in children: crashes with the same
ValueErrorunless the parent form'shas_changed()includes its nested formset. - Forgetting deletion checks: validating the nested formset of a row marked for deletion blocks the delete when an address row is incomplete, and saving it raises the same
ValueErrorwhen an address was added under that row. Guard both with_should_delete_form(). - Using
self.is_boundinadd_fields(): binds the nested formset insideempty_formand breaks JavaScript cloning after a failed submit; useform.is_bound. - Setting
extraorcan_deleteon the instance: those are factory arguments; passing them to the formset constructor raisesTypeError.
Building complex Django forms? We can help
Multi-level forms, dynamic formsets and large data-entry screens are exactly the kind of fiddly Django work we have shipped across 50+ projects since 2014. If your team is wrestling with nested formsets, wizard flows, or old Django form code that has to run on 5.2, our Django development services can design, build and test them, then hand them back to your team.
Frequently Asked Questions
Does Django have a built-in nested formset?
No. Django provides formset_factory, modelformset_factory and inlineformset_factory, but there is no built-in nested formset. You create one by attaching a child inline formset to each form of a parent inline formset, or by using the third-party django-nested-formset package.
Why do I get "ManagementForm data is missing or has been tampered with"?
Each formset level needs its own management_form, so with nested formsets you render the parent formset's management_form and every nested formset's management_form separately. A missing nested one, or two rows sharing a prefix, causes the error. Since Django 3.2 it is not raised as an exception: is_valid() returns False and the message appears in non_form_errors().
Why does saving raise "save() prohibited to prevent data loss due to unsaved related object"?
An address is being saved before its child has a primary key. Either the nested formset is saved before the parent formset, or a new child row was left blank while an address under it was filled in, so Django skipped the child. Save the parent formset first, and override the child form's has_changed() to include its nested formset so the blank row fails validation instead.
How do unique prefixes prevent formset collisions?
A formset's prefix namespaces all of its field names and its management_form. If two nested formsets share a prefix, Django cannot tell their POST data apart. Building each prefix from the parent form's form.prefix, for example f"{form.prefix}-{AddressFormset.get_default_prefix()}", gives every row its own names such as children-0-addresses-0-country.
What order should I save parents and children in?
Parents first. The parent formset's super().save() gives each new child a primary key; only then can the nested formset set a valid foreign key. Run the whole save inside transaction.atomic() so a failure part way through rolls everything back.
Should I use the django-nested-formset package or build it myself?
The package (0.1.4, last released in 2015) still passed our tests on Django 5.2.19 and suits a conventional two-level form. Build it yourself when you need three or more levels, custom validation, conditional nesting or fine control over prefixes. The mechanics are the same either way.
Can nested formsets go three levels deep?
Yes, but each extra level multiplies the complexity. You repeat the same pattern: override add_fields at each level, give each formset a unique prefix, render its own management_form, and save from the top down inside transaction.atomic(). Beyond two levels, consider splitting the workflow across pages instead.