Http404 is Django’s way to stop a view when a requested resource cannot be found. Django catches the exception and displays a 404 page instead of continuing normally. section 4.6.1
The usual path is get_object_or_404(): provide a model and lookup arguments, such as Musician and id=musician_id. One missing object—or a non-unique result—raises Http404. section 4.6.1
A typical request flows like this:
- Capture an integer from the URL, pass it into the view, and look up the corresponding object. section 4.6.1
- Render the object when it exists; otherwise, let Django handle the 404 response. section 4.6.1
- Treat URL arguments as untrusted input, because visitors can type values that do not identify valid objects. section 4.6.1
Musician detail view
A request for /bands/musician/100/ reaches the musician view. get_object_or_404(Musician, id=100) raises Http404 when no musician has that ID, producing a not-found page rather than an empty detail page. section 4.6.1
Listing 4.4 A view for displaying a Musician object based on an argument
# RiffMates/bands/views.py
from django.shortcuts import render, get_object_or_404 #1
from bands.models import Musician #2
def musician(request, musician_id):
musician = get_object_or_404(Musician, id=musician_id) #3
data = {
"musician": musician, #4
}
return render(request, "musician.html", data)
Use the complete view as a compact implementation pattern: import get_object_or_404(), retrieve the model instance, place it in template context, and render the detail template. section 4.6.1
