Handling 404 in Django
A 404 is the status for a page that does not exist. Django sends it when no view matches the address.
Raise Http404
This view raises Http404 for a name it does not know. The message names the problem.
from django.http import Http404, HttpResponse
def page(request, name):
if name != "about":
raise Http404("No such page.")
return HttpResponse("About this site")Fetch it or send a 404
This view fetches one post by its number. pk is the short name for the primary key.
from django.shortcuts import get_object_or_404
def post_detail(request, post_id):
post = get_object_or_404(Post, pk=post_id)
return HttpResponse(post.title)Ask for a missing post
The test client asks for post 9, which does not exist. The print shows the 404 status.
client = Client()
print(client.get("/post/9/").status_code)Ask for a known post and a missing one
The first ask finds post 1. The second ask finds nothing, so the status is 404.
print(client.get("/post/1/").content.decode())
print(client.get("/post/9/").status_code)Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.db import connection, models
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import path
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
Post.objects.create(title="First post", body="Hello from Django.")
def post_detail(request, post_id):
post = get_object_or_404(Post, pk=post_id)
return HttpResponse(post.title)
def page(request, name):
if name != "about":
raise Http404("No such page.")
return HttpResponse("About this site")
urlpatterns = [path("post/<int:post_id>/", post_detail), path("page/<str:name>/", page)]
from django.test import Client
client = Client()
print(client.get("/post/1/").status_code)
print(client.get("/post/1/").content.decode())
print(client.get("/post/9/").status_code)
print(client.get("/page/about/").content.decode())
print(client.get("/page/missing/").status_code)
print(client.get("/nope/").status_code)
Key points
- Http404: an error a view raises for a missing item.
- Use get_object_or_404 to fetch an object or send a 404.
- A missing address gives a 404 without a view.
- The test client prints the status with .status_code.
In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. The post view fetches one post by its number. A missing number sends a 404. The page view raises Http404 for an unknown name. The test client asks for a known post and a missing post. It also asks for a known page, a missing page, and an unknown address. The prints show the 200 status, the post title, and the 404 status three times.
Note
Raising Http404 stops the view at once.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does get_object_or_404 do when the object is missing?