get_object_or_404 is Django’s shortcut for fetching one database object while handling missing or invalid results as a 404 response. It keeps a view focused on the successful path: find the object, pass it to a template, and let Django stop the request when the lookup fails. section 4.12 section 4.6.1
A detail page usually receives an identifier from the URL. The view supplies the model and lookup criteria, commonly id=object_id. If exactly one object matches, the view continues; if none or multiple match, Django raises Http404 and displays a 404 page instead. section 4.6.1
The request flow is short:
- A URL pattern captures an integer such as musician_id. section 4.6.1
- The view calls get_object_or_404(Musician, id=musician_id). section 4.6.1
- A successful lookup supplies the musician object to the template. section 4.6.1
- A bad public URL becomes a 404 instead of an unhandled view failure. 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)
The complete view shows the essential pattern: import the shortcut, look up the model with the captured ID, build template data, and render the detail page. section 4.6.1
A musician detail URL
With the route bands/musician/<int:musician_id>/, a request such as /bands/musician/100/ reaches the musician view. If no Musician has ID 100, the shortcut raises Http404 and Django returns a page-not-found response rather than rendering musician.html. section 4.6.1
