By default, when your Django app runs into an error Django returns a page that looks something like this:
This is Django's default error message when debugging is enabled in your application (i.e. it is in development). This tutorial will help you create a custom error page for your Django web application.
Set DEBUG
to False
Notice the message at the bottom part of the page:
You're seeing this error because you have
DEBUG = True
in your Django settings file. Change that toFalse
, and Django will display a standard 404 page.
To disable debugging, go to your projects's settings.py
and set the value of the variable named DEBUG
to False
. Additionally, you might have to define allowed hosts for your application. This can be done by adding the hosts to the variable named ALLOWED_HOSTS
(usually found just under DEBUG
), like so:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
Once you've done this, visiting a page that doesn't exist will now lead you to a page that looks something like this:
This is Django's default error page in production. But if you like to change how this looks like, then follow these steps.
Add a handler for the error
There are a few variables that will override the default error views of Django, one of which is handler404
which overrides the Page Not Found view. Add this to your urls.py
file:
handler404 = 'your_app_name.views.entry_not_found'
where entry_not_found
is a function in views.py
that will render a page containing your custom error message, like this:
def entry_not_found(request, exception, template_name='404.html'):
return render(request, template_name)
Add the template
Now all you have left to do is populate 404.html
to contain your custom error message. Note that 404.html
should reside in your root templates
folder.
If you found this useful, consider buying me a coffee.
Top comments (0)