Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 77 ยท URLs and Views

Error Pages and Exceptions

Learn how Django turns exceptions into 404, 403 and 500 responses. Raise Http404 and PermissionDenied, write custom handler404 and handler500 views, and see DEBUG versus production.

Things go wrong on every real site: a visitor follows a dead link, a customer opens an order that is not theirs, a database connection drops. Django has a clear model for this. A view does not build an error page by hand. It raises an exception, and Django's request handler catches it and converts it into the right HTTP response with the right status code.

In this lesson you will raise Http404 and PermissionDenied, see what Django does with an unexpected crash, replace the default error pages with your own handlers, and learn how DEBUG changes everything. It follows on from Function-Based Views and Generic Display and Editing Views.

Exceptions become status codes

Django maps a few exception classes to HTTP statuses before your code ever sees them:

Raise this Response Meaning
django.http.Http404 404 Not Found The thing does not exist
django.core.exceptions.PermissionDenied 403 Forbidden It exists, but you may not have it
django.core.exceptions.BadRequest 400 Bad Request The request itself is malformed
SuspiciousOperation and subclasses 400 Tampering, e.g. a bad Host header
Any other exception 500 Internal Server Error A bug or a failing dependency
flowchart TD
    V["View runs"] --> OK{"Exception?"}
    OK -->|"no"| R["Normal response"]
    OK -->|"Http404"| H4["handler404"]
    OK -->|"PermissionDenied"| H3["handler403"]
    OK -->|"BadRequest"| H400["handler400"]
    OK -->|"anything else"| H5["log it, then handler500"]

Django's handler catches the exception and calls a small error view. You can replace each error view.

Two shortcuts save typing. get_object_or_404(Model, pk=pk) returns the object or raises Http404 for you, and get_list_or_404() does the same for lists. Generic views such as DetailView use them internally.

What the defaults do

The default 404 view looks for a template called 404.html in your template directories. If it exists, Django renders it with request_path in the context; if not, it falls back to a bare "Not Found" page. The 500 view uses 500.html, 403 uses 403.html, and 400 uses 400.html. This is the fastest way to brand your error pages: just add the templates.

Python Http404, PermissionDenied and a crash in production mode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the three failures. A missing book (an Http404 from your view) and an unknown URL (the resolver found no match) both render your 404.html. The PermissionDenied and the division by zero produce Django's built-in 403 and 500 pages, since no 403.html or 500.html exists. In the browser the visitor sees only the generic page; the real traceback goes to your logs, and the test Client(raise_request_exception=False) mimics that behavior. By default the test client re-raises the exception so that your tests fail loudly.

The message you pass to Http404("No such book") is not shown to visitors in production. It only appears on the debug page.

Writing your own handlers

When a template is not flexible enough, assign a view to a module-level name in the root URLconf: handler404, handler500, handler403 or handler400. The 404, 403 and 400 handlers receive (request, exception). The 500 handler receives only (request), because it must work even when most of the framework is broken.

A good use is returning JSON to API clients and HTML to browsers:

Python Custom handler404, handler403 and handler500

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep error handlers boring and safe. A 500 handler that queries the database or renders a template with context processors can fail with a second error, and then the visitor sees nothing useful. Return static HTML or a very simple template. Also remember the handlers are only used when DEBUG = False.

DEBUG versus production

With DEBUG = True, Django replaces its error pages with a rich technical page: the traceback, local variables, request data and settings. For a 404 it lists every URL pattern it tried. That is wonderful while developing and a disaster in production, where it leaks source paths, settings and SQL.

With DEBUG = False four things change:

  • The generic error pages (or your 404.html, 500.html, handlers) are shown.
  • ALLOWED_HOSTS must list your domain, otherwise every request is a 400.
  • Unhandled exceptions are logged to the django.request logger. Configure it so you actually see them; see Logging, Email and Internationalization for the LOGGING setting. Setting ADMINS with an email backend also mails you the traceback.
  • Django does not serve static files itself (Static Files and Media).

Never set DEBUG = True on a public server. The Security lesson includes it in the deployment checklist.

Exceptions you raise on purpose

A few patterns come up constantly:

Python
from django.core.exceptions import BadRequest, PermissionDenied
from django.shortcuts import get_object_or_404

def order_detail(request, pk):
    order = get_object_or_404(Order, pk=pk)
    if order.customer_id != request.user.id:
        raise PermissionDenied
    return render(request, "orders/detail.html", {"order": order})

For a customer asking for somebody else's order, some sites prefer 404 over 403 so that attackers cannot learn which ids exist. Both choices are valid; pick one deliberately.

LoginRequiredMixin and PermissionRequiredMixin redirect anonymous visitors to the login page. If you set raise_exception = True on them, they raise PermissionDenied instead, which becomes a 403. That is usually what an API wants, since an API client cannot follow a login form. The Authentication lesson covers the mixins.

Finally, do not use exceptions as flow control for ordinary cases. A search with no results is a normal page with an empty list, not a 404. Use Http404 when the URL names a specific thing that does not exist.

Exceptions you will meet in tracebacks

Django defines its own exceptions in django.core.exceptions and a few other modules. Recognizing them makes tracebacks much faster to read.

Exception Raised when
ObjectDoesNotExist Base class of every Model.DoesNotExist; catch it to handle "no such row" for any model
MultipleObjectsReturned get() matched more than one row
FieldDoesNotExist You ask a model's _meta for a field it does not have
FieldError A query uses an unknown field name or an invalid lookup
EmptyResultSet A query can never match (for example pk__in=[]); the ORM handles it internally and returns nothing, so you rarely see it
AppRegistryNotReady You import models or call apps.get_models() before django.setup() has loaded the apps
ImproperlyConfigured A setting is missing or wrong, such as an unusable DATABASES entry
ViewDoesNotExist A URL pattern refers to a view that cannot be imported
NoReverseMatch reverse() or {% url %} has no pattern for that name and arguments
DisallowedHost The Host header is not in ALLOWED_HOSTS
SuspiciousOperation Base class for security violations; Django turns it into a 400 response
PermissionDenied, Http404 Raised on purpose to produce a 403 or 404 page

The first few are the ones you handle in your own code; the rest signal that something needs fixing in configuration.

Python Triggering common Django exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same query errors appear in lookups and Q objects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A view raises Http404("No such book"). What does a visitor see in production?

    The message only appears on the debug page. In production the handler404 view renders 404.html or Django's plain default.
  2. 2. Which signature does a custom handler500 have?

    handler404, handler403 and handler400 receive the exception. handler500 takes only the request, because it must work when things are badly broken.
  3. 3. Where must handler404 be defined to take effect?

    Django looks for the handlerNNN names in the root URLconf module.
  4. 4. Which exception becomes a 403 response?

    django.core.exceptions.PermissionDenied maps to 403. BadRequest maps to 400, Http404 to 404 and other exceptions to 500.
  5. 5. What does the debug page expose that must never reach the public?

    With DEBUG = True Django shows source paths, variables and (filtered) settings, which would help an attacker.

Summary

  • Views signal problems by raising exceptions: Http404 (404), PermissionDenied (403), BadRequest (400); anything else becomes a 500.
  • get_object_or_404() is the usual way to raise 404 for a missing row.
  • Add 404.html, 403.html, 400.html and 500.html templates for quick branding, or assign views to handler404, handler403, handler400 and handler500 in the root URLconf.
  • handler500 receives only request; keep it simple and database-free.
  • DEBUG = True shows a technical page and must never be on in production; with DEBUG = False set ALLOWED_HOSTS and configure logging.
  • raise_exception = True on the auth mixins gives a 403 instead of a login redirect.

Next, move from views to the pages they render in Django Templates.