From be1f084d1841101800031dcd331f01d6bfdbdef3 Mon Sep 17 00:00:00 2001 From: "Terence D. Honles" Date: Thu, 23 Sep 2021 16:15:51 -0700 Subject: [PATCH] handle errors rendering with TemplateHTMLRenderer This change fixes an `OPTIONS` request to the API page which will return a successful response, but the `TemplateHTMLRender` will not be prepared to render it since there is no template name provided in either the view or response [1]. [1]: https://github.com/encode/django-rest-framework/blob/f0a5b958a134e8cd94e3ef3263e8fa623ac9b82f/rest_framework/renderers.py#L178-L189 --- src/drf_yasg/renderers.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/drf_yasg/renderers.py b/src/drf_yasg/renderers.py index 4540e7ef..77e87812 100644 --- a/src/drf_yasg/renderers.py +++ b/src/drf_yasg/renderers.py @@ -1,3 +1,4 @@ +from django.core.exceptions import ImproperlyConfigured from django.shortcuts import resolve_url from django.template.loader import render_to_string from django.utils.encoding import force_str @@ -64,10 +65,15 @@ class _UIRenderer(BaseRenderer): def render(self, swagger, accepted_media_type=None, renderer_context=None): if not isinstance(swagger, Swagger): # pragma: no cover - # if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response`` - # in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it - # see https://github.com/axnsan12/drf-yasg/issues/58 - return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context) + try: + # if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response`` + # in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it + # see https://github.com/axnsan12/drf-yasg/issues/58 + return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context) + except ImproperlyConfigured: + # Fall back to using eg '404 Not Found' + response = renderer_context['response'] + return '%d %s' % (response.status_code, response.status_text.title()) self.set_context(renderer_context, swagger) return render_to_string(self.template, renderer_context, renderer_context['request'])