Raising Http404
Part of the Django Basics section of Coddy's Django journey. Lesson 9 of 23.
Open /drinks/mocha/. The route matches, but DRINKS["mocha"] raises a KeyError, and the site answers with status 500, a server error. To a visitor, your site looks broken.
The right answer is 404, no such page. A view says so by raising Http404. The café has twelve tables, so the table view could refuse /table/40/:
from django.http import Http404, HttpResponse
def table(request, number):
if number > 12:
raise Http404(f"There is no table {number}")
...raise, not return: Http404 is an exception, and Django turns it into the usual 404 page. Returning HttpResponse("No such page") shows the words with status 200, which tells browsers and search engines the page exists.Challenge
EasyMake the drink view raise Http404 when the slug is not in DRINKS. /drinks/latte/ keeps working.
Press Run: the preview opens /drinks/mocha/, which now shows the 404 page with your message.
Try it yourself
from django.http import HttpResponse
DRINKS = {
"espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
"latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
"flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
"hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}
def home(request):
return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")
def about(request):
return HttpResponse("Corner Café opened in 2026.")
def hours(request):
return HttpResponse("Open every day from 8:00 to 18:00.")
def contact(request):
return HttpResponse("Write to us at hello@cornercafe.example.")
def table(request, number):
return HttpResponse(f"<h1>Table {number}</h1>")
def drink(request, slug):
item = DRINKS[slug]
return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")
def order(request):
size = request.GET.get("size", "medium")
if size not in ["small", "medium", "large"]:
size = "medium"
return HttpResponse(f"You ordered a {size} coffee.")
All lessons in Django Basics
Practice on your own: Django playground