Opened 3 years ago
Closed 3 years ago
#33179 closed Cleanup/optimization (wontfix)
Show helpful error message when first argument to shortcuts.render is not request
Reported by: | Joel Sleppy | Owned by: | Joel Sleppy |
---|---|---|---|
Component: | HTTP handling | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
This is one of a class of changes I'm interested in making, so please also comment on if developer experience/error message improvements like this are wanted in general.
I recently started a new Django project and got frustrated at tiny mistakes I made that were difficult to find because of opaque error messages.
Currently, writing this:
def render_view_missing_request(request): return render('shortcuts/render_test.html')
leads to:
TypeError: render() missing 1 required positional argument: 'template_name'
which is very confusing because the developer did provide the template name, but nothing can be done about this as far as I know without changing the function signature. Please let me know if there's a way to handle this case nicely, though.
Writing another common variation:
def render_view_missing_request(request): return render('shortcuts/render_test.html', {'foo': 'FOO'})
leads to:
TypeError: join() argument must be str or bytes, not 'dict'
which is easier to figure out given the stack trace, but still unhelpful to a newcomer.
I propose inspecting the first argument's class name to return a message like this:
"First argument to render() must be an HttpRequest, not 'str'."
Similar type inspection is done in other shortcut functions such as get_object_or_404
.
Change History (5)
comment:1 by , 3 years ago
Owner: | changed from | to
---|
comment:2 by , 3 years ago
comment:3 by , 3 years ago
Description: | modified (diff) |
---|
comment:4 by , 3 years ago
Description: | modified (diff) |
---|
comment:5 by , 3 years ago
Component: | Uncategorized → HTTP handling |
---|---|
Resolution: | → wontfix |
Status: | assigned → closed |
Type: | New feature → Cleanup/optimization |
While this sort of check can be useful, we have to be judicious. Type checking prevents duck typing and also imposes a performance penalty. In this case, I don't think the ease of debugging the usage mistakes outweighs the drawback of an extra isinstance
check on every request. You can write to the DevelopersMailingList if you want to discuss the idea with a wider audience.
PR opened here https://github.com/django/django/pull/14961