Creating Custom 404 Page in Python Django

When we develop a web application with Django, the user may enter a url that does not exist. In this case, Django will present the user with a standard 404 page that is not stylish. Instead, we can create custom 404 page in Django.

You can learn how to create custom 404 page by following the steps below.

Step 1

In order to see the 404 page we created, it is necessary to change DEBUG status to False in

DEBUG = False

Step 2

Next we need to create an alternative 404.html page. We have to create this file in a location we want in the folder where our templates are.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),],  # Templates pathway
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

Step 3

There are predefined handler methods inside the django.urls functions.
To change this, we add the following line of code to our file;

from django.urls import path
from main.views import *

handler404 = 'main.views.handler404'  #add to file

app_name = "main"

urlpatterns = [
    path('', home, name="home"),

We are crushing the existing handler404 function with the handler404 function that will work in this way.

Step 4

We define our handler404 function in the file in our main app.

# 404 PAGE 
def handler404(request, exception=None):
    return render(request, 'auth/404.html')

In the picture below, you can see the location of the file in our main app and the file structure of our templates where our 404.html page is located.

After completing these steps, you can view the 404 page by entering a url that there is not in your application from the browser.