Custom 403 error page in django rest framework

Viewed 1639

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.

3 Answers

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

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

try this:

from django.shortcuts import render
def handler403(request, exception, template_name='403.html'):
    return render(request, '403.html')
Related