Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 403 error page in django rest framework

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.

like image 803
Xantho Avatar asked Oct 14 '25 09:10

Xantho


1 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
like image 84
Nikolaos Paschos Avatar answered Oct 16 '25 21:10

Nikolaos Paschos