Opened 5 years ago

Closed 5 years ago

#30404 closed Cleanup/optimization (worksforme)

"Using a model formset in a view" example doesn't handle invalid formset.

Reported by: Stephen G Tuggy Owned by: nobody
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The URL is here: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-model-formset-in-a-view The 2.2 and 1.8 documentation versions suffer from the same problem (and probably every other version in between).

You will notice that the Method-Based View manage_authors handles the case where request.method == 'POST' and formset.is_valid(), but not the case where request.method == 'POST' and formset is not valid. As a result, newbies (like myself) following this example may not implement this case either. Then, if the data POSTed to this view passes client-side validation but not server-side validation, the user will get an error message:

The view '...' didn't return an HttpResponse object. It returned None instead

See this StackOverflow post, for example: https://stackoverflow.com/questions/50202477/the-view-blog-views-post-list-didnt-return-an-httpresponse-object-it-returned?rq=1 And this post: https://www.freecodecamp.org/forum/t/didnt-return-an-httpresponse-object-it-returned-none-instead/216155/2

As far as I have been able to determine, the correct code behavior in this situation is pretty much the same as what you do for a GET: Construct a context dictionary, starting with RequestContext, then return the result of rendering the formset once more. One caveat: Make sure your template has a spot to display non-field errors.

Is this correct? Thank you for your attention.

Change History (1)

comment:1 by Mariusz Felisiak, 5 years ago

Resolution: worksforme
Status: newclosed
Summary: Docs: "Using a model formset in a view" example does not handle the case where validation fails on POST"Using a model formset in a view" example doesn't handle invalid formset.
Type: BugCleanup/optimization

Thanks for the report, however this code works for me. Please notice that return is outside if ... else block, so it is called even when form is invalid:

if request.method == 'POST':
    ...
else:
    ...
return render(request, 'manage_authors.html', {'formset': formset})

Maybe some indentation issue?

Please use one of support channels.

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