Django Custom Error Pages
A custom error page is a page written in the site voice. It replaces the plain page Django sends for an error.
Write the handler
This view takes the request and the error. It returns a friendly page with the status 404.
from django.http import HttpResponse
def page_not_found(request, exception):
return HttpResponse("<h1>Page not found</h1><p>Try the home page.</p>", status=404)Name the handler
This line tells Django which view handles missing pages. The name goes in the URL file.
handler404 = page_not_foundKeep the page in a template
A real project keeps the page in a template file. The handler renders it with the status 404.
from django.shortcuts import render
def page_not_found(request, exception):
return render(request, "404.html", status=404)Ask for a missing page
The test client asks for /nope/, which matches no route. The prints give the 404 status and the friendly page.
client = Client()
print(client.get("/nope/").status_code)
print(client.get("/nope/").content.decode())The home page still works
The handler only runs for missing pages. The home page answers as before.
print(client.get("/").content.decode())Example
import django
from django.conf import settings
settings.configure(DEBUG=False, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
def home(request):
return HttpResponse("Home page")
def page_not_found(request, exception):
return HttpResponse("<h1>Page not found</h1><p>Try the home page.</p>", status=404)
handler404 = page_not_found
urlpatterns = [path("", home)]
from django.test import Client
client = Client()
print(client.get("/nope/").status_code)
print(client.get("/nope/").content.decode())
print(client.get("/").content.decode())
Key points
- handler404 names the view for missing pages.
- The handler takes the request and the error.
- The handler returns a page with the status 404.
- A template can hold the page, like other pages.
In this example, the setup lines configure Django. DEBUG is False here, so the custom page shows. The next lesson explains DEBUG. The home view returns the home page. The handler returns a friendly page with the status 404. The line handler404 = page_not_found tells Django to use it. The test client asks for a missing page and then the home page. The prints show the 404 status, the friendly page, and the home page.
Note
The handler runs for every missing address.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does Django learn which view handles missing pages?