Fix AttributeError in base.html when called without response_headers

This happens when using a `404.html` which extends DRF's `base.html` and is called by a `Resolver404`.
Since `Resolver404` goes via django's `handler404` and not via DRF's exception handling,
it doesn't get the extra context.

Since the `|items` filter doesn't check for `response_headers` being null (missing) it attempts
to call `<None>.items()`, thus raising an AttributeError.

Originally I solved this in the template by guarding the `for` loop with a `if response_headers`.
However @rpkilby expressed a preference for doing the check inside the `items` filter instead.
This commit is contained in:
Craig de Stigter 2018-05-10 12:11:38 +12:00
parent c17b4ad0d0
commit 90126627eb
2 changed files with 11 additions and 0 deletions

View File

@ -240,6 +240,10 @@ def items(value):
lookup. See issue #4931
Also see: https://stackoverflow.com/questions/15416662/django-template-loop-over-dictionary-items-with-items-as-key
"""
if value is None:
# `{% for k, v in value.items %}` doesn't raise when value is None or
# not in the context, so neither should `{% for k, v in value|items %}`
return []
return value.items()

7
tests/test_templates.py Normal file
View File

@ -0,0 +1,7 @@
from django.shortcuts import render
def test_base_template_with_no_context():
# base.html should be renderable with no context,
# so it can be easily extended.
render({}, 'rest_framework/base.html')