[I have posted this at the Django users | Google Groups also.]
Using the example in the inline formset docs, I am able to edit objects belonging a particular model (using modelforms). I have been trying to follow the same pattern for creating new objects using inline formsets, but have been unable to clear my head enough to bring out a working view for this purpose.
Using the same example as in the above link, how would I go about creating a new instance of an "Author" model together with its related "Book" objects?
models.py (Contact)
models.py (Link)
forms.py
views.py
This is not based on the example in the book, it's edited down from some code on my site. I haven't tested it so there might be some bugs but overall it should be solid. Using an empty instance of Contact isn't the suggested method but it saves a bit of logic and it works.
Edit: Added Link Model, switched to normal Foreign Key instead of Generic Foreign Key which is confusing
First, create a Author model form.
then create a dummy author object:
Then create a inline formset using the dummy author like so:
Send that off to a template. After the data is returned back to the view, you create the Author:
Now hook the inline formset in with the newly created author and then save:
edit:
To have no checkboxes on new forms, do this is a template:
I'd actually like to propose a small adjustment to nbv4's solution:
Assume that you don't create the empty created_author outside of the if-else statement and thus need to nest the formset inside the author_form.is_valid() to avoid runtime errors when the author_form is not valid (and thus no created_author is instantiated).
Instead of:
Do the following:
This version avoids committing the created_author until the book_formset has had a chance to validate. The use case to correct for is that someone fills out a valid AuthorForm with an invalid BookFormSet and keeps resubmitting, creating multiple Author records with no Books associated with them. This seems to work for my project-tracker app (replace "Author" with "Project" and "Book" with "Role").