Opened 14 years ago
Closed 12 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 |
Description
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
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(): formset.save() # Do something. formset = BookInlineFormSet(instance=author) return render_to_response("manage_books.html", { "formset": formset, })
Change History (5)
comment:1 by , 14 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:2 by , 14 years ago
Severity: | → Normal |
---|---|
Type: | → Bug |
comment:5 by , 12 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
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.