Multiples of one formset

Just following up on this - I found the project I was thinking of, but it’s not quite a great parallel and quite frankly a bit of a mess. (It’s a module that has been worked on by 3 different people, and it shows.)

About the best I can say about it is that it does use inline formsets with custom prefixes for each.
There are sets of nested loops, where the constructor for the child formset has the parent formset’s prefix passed to it, and concatenated with it to make them all unique.
The format is pretty generic - the topmost level prefix is “t-”, which means each form has IDs like “t-0”, “t-1”, etc.
Each one of those forms is responsible for creating instances of a 2nd level form, which uses a prefix of “-r-” appended to the parent’s prefix so you end up with IDs like t-1-r-0, t-1-r-1, etc.
Finally, each one of those is responsible for creating a 3rd level formset, which uses a prefix of “-d-”, which results in IDs that end up looking like “t-1-r-0-d-0”, “t-1-r-0-d-1”, etc.

Now, since any one of these levels can have forms added to it, the JavaScript has to do a fair amount of work to figure out what the right prefixes need to be for the additions. We’ve created a couple of views that take the current prefix, and using the formset’s empty_form attribute, modifies the prefix to the right values before passing it back out to the client, which the JavaScript then injects into the proper location within the page.

The view which take the submission processes all the forms manually - there’s work that needs to be done with all the entries, it’s not just stored as data in the database. So we iterate through each form, which iterates through each 2nd level form, which iterates through each 3rd level form to process the individual entries. If we didn’t have to do that work, I believe we could just save the top level form and let Django do the rest - but that’s just conjecture on my part.

Bottom line is that it did turn out to be quite a bit of work, but it does work for us.

1 Like