Skip to content

/codes/django/django-http-response-classes

Django HttpResponse subclasses and their status codes

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
tool
Django
versions
Django 4.2 – 6.1
os
any

Django ships an HttpResponse subclass for the common status codes, so a view can return HttpResponseNotFound() instead of setting status=404 by hand. For 404 the idiomatic way is to raise Http404, which Django turns into a 404 page; for other codes pass status= to HttpResponse or JsonResponse.

The classes, with the status codes they send

bash
python -c '
import django
from django.conf import settings
settings.configure(SECRET_KEY="dev")
django.setup()
from django import http
for name in ["HttpResponse", "HttpResponseRedirect", "HttpResponsePermanentRedirect", "HttpResponseNotModified",
             "HttpResponseBadRequest", "HttpResponseForbidden", "HttpResponseNotFound", "HttpResponseNotAllowed",
             "HttpResponseGone", "HttpResponseServerError", "JsonResponse"]:
    cls = getattr(http, name)
    if name in ("HttpResponseRedirect", "HttpResponsePermanentRedirect"): r = cls("/new/")
    elif name == "HttpResponseNotAllowed": r = cls(["GET", "POST"])
    elif name == "JsonResponse": r = cls({"ok": True})
    else: r = cls()
    print(f"{name:32} {r.status_code}")'

Output

HttpResponse                     200
HttpResponseRedirect             302
HttpResponsePermanentRedirect    301
HttpResponseNotModified          304
HttpResponseBadRequest           400
HttpResponseForbidden            403
HttpResponseNotFound             404
HttpResponseNotAllowed           405
HttpResponseGone                 410
HttpResponseServerError          500
JsonResponse                     200

Usage

python
from django.http import Http404, HttpResponseNotAllowed, JsonResponse

def article(request, pk):
    if request.method not in ("GET", "HEAD"):
        return HttpResponseNotAllowed(["GET", "HEAD"])   # also sets the Allow header
    try:
        item = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        raise Http404("No such article")                # rendered with 404.html
    return JsonResponse({"title": item.title}, status=200)

Any other code: HttpResponse(status=429) or JsonResponse(data, status=422). django.shortcuts.get_object_or_404() combines the lookup and the Http404.

Sources