Categories
Python Answers

How to create a custom 500/404 error page with Python Django?

Spread the love

To create a custom 500/404 error page with Python Django, we can set the response object to the error code we want and return it.

For instance, we write

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


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


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

to call render_to_response with the template URL to create the response object.

And then we set the status_code to 404 or 500.

Then we return it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *