Opened 6 years ago

Closed 4 years ago

#14917 closed Bug (fixed)

Error in the sample code under "Using an inline formset in a view"

Reported by: baddox Owned by: nobody
Component: Documentation Version: 1.2
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I believe the sample code under the above linked paragraph should have the "formset = BookInlineFormSet(instance=author)" line executed regardless of the request method. Following the example as it is now, the page reload after filling in one of the extra forms and saving will have one fewer than the specified number of extra forms. Similarly, the page reload after marking a bound form for deletion and saving will still have that just-deleted form present in the formset. Moving the formset variable assignment outside of and after the "if request.method == "POST":" block (and thus getting rid of the "else:" block) fixes this problem. The entire corrected sample code would be as such:

def manage_books(request, author_id):
    author = Author.objects.get(pk=author_id)
    BookInlineFormSet = inlineformset_factory(Author, Book)
    if request.method == "POST":
        formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
        if formset.is_valid():
            # Do something.
    formset = BookInlineFormSet(instance=author)
    return render_to_response("manage_books.html", {
        "formset": formset,

Change History (5)

comment:1 Changed 6 years ago by Gabriel Hurley

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted

This isn't quite right.

The problem with what you propose is that if you POST the form but it's not valid, you then overwrite formset and return a form without any of the changed data, errors, etc.

In general, the "do something" in that example would be to return a redirect if the formset is valid and saved, and to return the formset with the errors and changed data if it is invalid.

So the solution here is actually to flesh out the "do something" in the example, not to change the formset instantiation.

comment:2 Changed 6 years ago by James Addison

Severity: Normal
Type: Bug

comment:3 Changed 5 years ago by Aymeric Augustin

UI/UX: unset

Change UI/UX from NULL to False.

comment:4 Changed 5 years ago by Aymeric Augustin

Easy pickings: unset

Change Easy pickings from NULL to False.

comment:5 Changed 4 years ago by Claude Paroz <claude@…>

Resolution: fixed
Status: newclosed

In [19a810b18cacea12f201b5a235d1af9218d9c2e9]:

Fixed #14917 -- Hinted that view should redirect after form post success

Note: See TracTickets for help on using tickets.
Back to Top