Fix get_template_context to handle also lists (#9467)

This commit is contained in:
Devid 2024-07-15 17:03:40 +01:00 committed by GitHub
parent ccfe0a9637
commit f74185b6dd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 0 deletions

View File

@ -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

View File

@ -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):