Customize error 404 page in django

Dec 11, 2023    |   

1. Make changes to settings.py file of your application:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']

 

2.  Edit urls.py file of your application and add the below code:

# handling the 404 error
# change app_name to name of your real application
handler404 = 'app_name.views.error_404_view'

Be sure to change app_name to name of your real application.

 

3. Open up the views.py  of your app and add the below code: 

from django.conf import settings
from django.shortcuts import redirect
 
def error_404_view(request, exception):
    return render(request, '404.html')

 

4. Now add '404.html' file under 'templates' of your application.

The HTML content of '404.html' is what you want to show as a customized error 404 page.

 

But using customized 404.html may causeAPPEND_SLASH not work. You can restart django server or manually add APPEND_SLASH = True to fix it.