Nested formsets with Django

I have recently needed to use nested formsets. After reading this blog post, I started coding away like the example suggests.

I however, ran into an issue that took me an hour to solve, but was quite trivial (from a solution’s point of view). I was getting an error from the management form saying that the “data is missing or has been tampered with”.

After a bit of debugging, I found the issue: passing

data =
when creating the nested formset, raises the error, even if the data is an empty dictionary. Removing it, solves the error but does not pass on data from the user to the form, for validation.

The solution was to only pass the data if it exists (see edit 1):

data = if else None

Edit 1: In order to use the empty_form feature of formsets, the above line must be changed to:

data = if and index is not None else None

The same applies for using uploaded files:

files = self.files if self.files and index is not None else None

Saturday, June 30, 2012 — 1 note   ()
  1. andreipetre posted this