Skip to content

Commit

Permalink
Fix get_template_context to handle also lists (#9467)
Browse files Browse the repository at this point in the history
  • Loading branch information
sevdog committed Jul 15, 2024
1 parent ccfe0a9 commit f74185b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ def resolve_template(self, template_names):

def get_template_context(self, data, renderer_context):
response = renderer_context['response']
# in case a ValidationError is caught the data parameter may be a list
# see rest_framework.views.exception_handler
if isinstance(data, list):
return {'details': data, 'status_code': response.status_code}
if response.exception:
data['status_code'] = response.status_code
return data
Expand Down
14 changes: 14 additions & 0 deletions tests/test_htmlrenderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.exceptions import ValidationError
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response

Expand All @@ -34,10 +35,17 @@ def not_found(request):
raise Http404()


@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def validation_error(request):
raise ValidationError('error')


urlpatterns = [
path('', example),
path('permission_denied', permission_denied),
path('not_found', not_found),
path('validation_error', validation_error),
]


Expand Down Expand Up @@ -91,6 +99,12 @@ def test_permission_denied_html_view(self):
self.assertEqual(response.content, b"403 Forbidden")
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')

def test_validation_error_html_view(self):
response = self.client.get('/validation_error')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.content, b"400 Bad Request")
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')

# 2 tests below are based on order of if statements in corresponding method
# of TemplateHTMLRenderer
def test_get_template_names_returns_own_template_name(self):
Expand Down

0 comments on commit f74185b

Please sign in to comment.