diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index ea73c6657..b81f9ab46 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -171,6 +171,10 @@ class TemplateHTMLRenderer(BaseRenderer): 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 diff --git a/tests/test_htmlrenderer.py b/tests/test_htmlrenderer.py index fa0f4efc6..aa0cfb19c 100644 --- a/tests/test_htmlrenderer.py +++ b/tests/test_htmlrenderer.py @@ -8,6 +8,7 @@ from django.urls import path 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 @@ -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), ] @@ -91,6 +99,12 @@ class TemplateHTMLRendererTests(TestCase): 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):