Handle 404 Not Found Page in Django

This post shows how to customize your Django website’s 404 (not found) page.

If the resource doesn’t exist, Django displays the standard 404 page in production mode (DEBUG = False). Django invokes a specific view that is added to handle 404 failures when the Http404 exception is raised in a view. Django’s handler404 view by default is django.views.defaults.page not found (). If you added the template 404.html to your root template directory, this view either returns a “Not Found” message or a “Not Found” message instead.

Let’s create custom 404.html page and create function to server this template. First of all please ensure that you have DEBUG = FALSE in your setting.py.

Create 404.html page

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Page Not Found</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
    <div class="text-center">
    <h1>404 Error</h1>
    <p>The requested resource was not found on this server</p> 
    <a href="/" class="btn btn-info">Go back to home</a>
    </div>
</div>
</body>
</html>

Create Url in url.py file


from django.urls import include, path
urlpatterns = [
    path('', include('appAdmin.urls')),
]

# handling the 404 error
handler404 = 'appAdmin.views.error_404_view'

Create view to render page

from django.conf import settings 
from django.shortcuts import render,redirect

# Create your views here.
def error_404_view(request, exception):
    return render(request, '404.html')

All done it’s time to unknown url request and you get output will be like this.

That is it for today, hope it helps.
If you have any suggestion for this article. please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Handle 404 Not Found Page in Django

Leave a Reply

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

Scroll to top