Examples


Django 404 Page Not Found


Page Not Found

In Django, a "404 Page Not Found" error shows that the requested URL does not match any of the URLs defined in your Django project's URL configuration.

1. Check the URL Pattern

urls.py

Ensure that the URL you’re visiting matches a path defined in your urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('home/', views.home, name='home'),
]

Visiting /home/ will work, but /homepage/ will give a 404.

2. Check the View Function

Make sure the corresponding view function exists and returns an HTTP response

views.py
from django.http import HttpResponse
from django.shortcuts import render

def home(request):
    return HttpResponse("Welcome to the homepage!")

def page_not_found(request, exception):
    return render(request, "404.html", status=404)

3. Include App URLs in the Project

If you're working in a project with multiple apps, ensure the app's URLs are included in the myproject/urls.py

project/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),  # include app URLs here
]

4. Trailing Slashes

By default, Django redirects URLs without trailing slashes if APPEND_SLASH = True (default)

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

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '127.0.0.1']

5. Create 404 Page

  • Create 404.html file in templates folder
  • Customize the file and fill with whatever you want.
<html>
    <head>
        <title>Page Not Found - 404</title>
        <style>
            body { 
                text-align: center; 
                padding: 50px; 
                font-family: Arial, sans-serif; 
            }
            h1 { 
                font-size: 50px; 
            }
            p { 
                font-size: 20px; 
            }
        </style>
    </head>
    <body>
        <h1>404</h1>
        <p>Oops! The page you're looking for doesn't exist.</p>
        <a href="/home">Go Back Home</a>
    </body>
</html>

Output

In the browser window, type 127.0.0.1:8000/home/ inside the address bar.

Django 404 Home Page

Triggering a 404 Error in the Browser

In the browser window, type 127.0.0.1:8000/sdsdsd/ inside the address bar. This will simulate a 404 error, displaying your custom page if setup correctly.

Django 404 Page Not Found

Prev Next