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
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.
data = self.data
The solution was to only pass the data if it exists (see edit 1):
data = self.data if self.data else None
Edit 1: In order to use the
empty_form feature of formsets, the above line must be changed to:
data = self.data if self.data 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