4

I am trying to override the default 403.html template of django rest framework, by declaring in ulrs.py handler403 = 'my_app.views.handler403'.

And in the app's views.py:

def handler403(request, exception, template_name='403.html'):
    response = render_to_response('403.html', {})
    response.status_code = 403
    return response

The template's directory is included in TEMPLATE_DIRS in settings.py. However, making a request to an endpoint that has IsAdminUser permission, renders the default drf template.

The same exact procedure for the 404 exception works perfectly fine.

Any answer I saw in the web did not help me resolve the issue.

Xantho
  • 65
  • 7

3 Answers3

4

It's quite simple actually:

You have to overwrite 'custom_exception_handler' of the DRF just like below:

from Django.shortcuts import render_to_response

def custom_exception_handler(...):
    response = render_to_response('path/to/template/403.html', {})
    response.status_code = 403
    return response
Community
  • 1
  • 1
Nikolaos Paschos
  • 406
  • 4
  • 12
0

It does not work because DRF returns a json response, does not render a template.

cgl
  • 1,106
  • 1
  • 13
  • 27
  • So any solution to my problem? – Xantho Sep 18 '18 at 17:38
  • Depends, do you really want to return an HTML response instead of a JSON response as a part of your api? – cgl Sep 19 '18 at 09:35
  • Yes, when a 403 appears I want to render a custom template – Xantho Sep 19 '18 at 10:17
  • Ok following this answer https://softwareengineering.stackexchange.com/a/344112 I think if you share your view I can help you with it. Please edit your question with your view code snippet. – cgl Sep 19 '18 at 10:25
0

try this:

from django.shortcuts import render
def handler403(request, exception, template_name='403.html'):
    return render(request, '403.html')
ayush gupta
  • 162
  • 8