Add failing tests and fix for dict that have a key items #4931 (#4932)

This commit is contained in:
Tim Watts 2017-03-03 10:23:09 +01:00 committed by Tom Christie
parent 35bccaab90
commit 8df340908b
5 changed files with 60 additions and 5 deletions

View File

@ -1,7 +1,7 @@
{% load rest_framework %}
<table class="table table-striped">
<tbody>
{% for key, value in results.items %}
{% for key, value in results|items %}
{% if key in details %}
<tr><th>{{ key|capfirst }}</th><td {{ value|add_nested_class }}>{{ value|format_value }}</td></tr>
{% endif %}

View File

@ -1,10 +1,10 @@
{% load rest_framework %}
<table class="table table-striped">
<tbody>
{% for key, value in value.items %}
{% for k, v in value|items %}
<tr>
<th>{{ key|format_value }}</th>
<td>{{ value|format_value }}</td>
<th>{{ k|format_value }}</th>
<td>{{ v|format_value }}</td>
</tr>
{% endfor %}
</tbody>

View File

@ -6,7 +6,7 @@
<tbody>
{% for row in results %}
<tr>
{% for key, value in row.items %}
{% for key, value in row|items %}
{% if key in columns %}
<td {{ value|add_nested_class }} >
{{ value|format_value }}

View File

@ -163,6 +163,17 @@ def format_value(value):
return six.text_type(value)
@register.filter
def items(value):
"""
Simple filter to return the items of the dict. Useful when the dict may
have a key 'items' which is resolved first in Django tempalte dot-notation
lookup. See issue #4931
Also see: https://stackoverflow.com/questions/15416662/django-template-loop-over-dictionary-items-with-items-as-key
"""
return value.items()
@register.filter
def add_nested_class(value):
if isinstance(value, dict):

View File

@ -648,3 +648,47 @@ class AdminRendererTests(TestCase):
assert result == ''
assert response.status_code == status.HTTP_303_SEE_OTHER
assert response['Location'] == 'http://example.com'
def test_render_dict(self):
factory = APIRequestFactory()
class DummyView(APIView):
renderer_classes = (AdminRenderer, )
def get(self, request):
return Response({'foo': 'a string'})
view = DummyView.as_view()
request = factory.get('/')
response = view(request)
response.render()
self.assertInHTML('<tr><th>Foo</th><td>a string</td></tr>', str(response.content))
def test_render_dict_with_items_key(self):
factory = APIRequestFactory()
class DummyView(APIView):
renderer_classes = (AdminRenderer, )
def get(self, request):
return Response({'items': 'a string'})
view = DummyView.as_view()
request = factory.get('/')
response = view(request)
response.render()
self.assertInHTML('<tr><th>Items</th><td>a string</td></tr>', str(response.content))
def test_render_dict_with_iteritems_key(self):
factory = APIRequestFactory()
class DummyView(APIView):
renderer_classes = (AdminRenderer, )
def get(self, request):
return Response({'iteritems': 'a string'})
view = DummyView.as_view()
request = factory.get('/')
response = view(request)
response.render()
self.assertInHTML('<tr><th>Iteritems</th><td>a string</td></tr>', str(response.content))