liveBook · Manning

Http404

As explained in Django in Action

Http404 is a Django exception indicating that a requested resource or object could not be found.

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

How Django in Action covers it

How deep it goes
Explains automatic exception handling, lookup failure, URL capture, and customization, but defers production configuration details.
Examples
Demonstrates a Musician detail view and a missing musician with ID 100.
What it assumes
Uses Django models, views, URL arguments, templates, and render() in the implementation pattern.
What you can do after
Operate Django views that safely retrieve objects and return not-found pages for invalid URL arguments.
How it connects
Connects get_object_or_404(), Django views, URL routing, model lookups, templates, and HTTP 404 responses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.