How to create a custom 404/500 error page in django

created at 07-17-2021 views: 12

Add your own custom implementation of the following two views under under your main content, and set the templates 404.html and 500.html and the content you want to display.


from django.shortcuts import render_to_response
from django.template import RequestContext

def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
    response.status_code = 404
    return response

def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
    response.status_code = 500
    return response

Handler404 and handler500 export the Django string configuration variable django/conf/urls/ This is the reason for the above configuration.

To make the above configuration effective, you should define the following variables in the file, and point the exported Django variables to the string Python path that defines these Django functional views, as shown below:

Add the following code in

from django.conf.urls import (
handler400, handler403, handler404, handler500

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

Django 2.0 update

The signature of the handler view has been changed in Django 2.0:

If you use the above view, handler404 will fail with the following message:

"Handler404() got an unexpected keyword parameter'exception'"

Modify your view in this case as follows:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response("404.html")
    response.status_code = 404
    return response

Intractable diseases

Don't forget that DEBUG must be set to False to make these work, otherwise, the normal debug handler will be used.

created at:07-17-2021
edited at: 07-17-2021: