API Reference¶
Response classes for every HTTP status code (RFC 9110).
All classes are subclasses of Django’s HttpResponse <https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponse>_.
Import from here to get every status-code class in one place; see each
class’s docstring for when to use it.
HttpResponse* — For HTML, plain text, or arbitrary content. These
classes (e.g. :class:HttpResponseOK, :class:HttpResponseCreated) extend
HttpResponse <https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponse>_ and set the appropriate status code (and
headers where the spec requires it).
JsonResponse* — For JSON APIs. These classes (e.g. :class:JsonResponseOK,
:class:JsonResponseCreated, :class:JsonResponseBadRequest) extend Django’s
JsonResponse <https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.JsonResponse>_ and set the status code; pass a dict (or
other JSON-serialisable data) as the first argument.
Example (HttpResponse)::
from django_allresponses import (
HttpResponseOK,
HttpResponseNoContent,
HttpResponseCreated,
)
def my_view(request):
if request.method == "GET":
return HttpResponseOK("<html>...</html>")
if request.method == "DELETE":
do_delete()
return HttpResponseNoContent()
new = create_resource()
return HttpResponseCreated(location=new.get_absolute_url(), created_document=new.get_created_document())
Example (JsonResponse)::
from django_allresponses import JsonResponseOK, JsonResponseCreated
def api_view(request):
return JsonResponseCreated({"id": 1, "name": "New"}, location="/api/items/1")
HttpResponseAccepted
¶
Bases: HttpResponse
202 Accepted.
Use when you've accepted the request but haven't finished (e.g. you queued a background job). The client can't assume the action will succeed.
Example::
queue_export_task(project_id)
return HttpResponseAccepted()
Source code in django_allresponses/responses.py
HttpResponseBadGateway
¶
Bases: HttpResponse
502 Bad Gateway.
Use when you're a gateway/proxy and the upstream server returned invalid or no response. Usually sent by the reverse proxy, not Django.
Source code in django_allresponses/responses.py
HttpResponseBadRequest
¶
Bases: HttpResponseBadRequest
400 Bad Request.
Use when the request is malformed or invalid (bad syntax, invalid JSON, etc.).
Example::
return HttpResponseBadRequest("Invalid JSON body")
Source code in django_allresponses/responses.py
HttpResponseConflict
¶
Bases: HttpResponse
409 Conflict.
Use when the request conflicts with current state (e.g. concurrent edit, version mismatch). Include enough info so the client can retry.
Example::
return HttpResponseConflict("Resource was modified by another user")
Source code in django_allresponses/responses.py
HttpResponseContentTooLarge
¶
Bases: HttpResponse
413 Content Too Large.
Use when the request body is too big. Optionally pass retry_after
(seconds or datetime) when the condition might be temporary.
Args: retry_after: Optional. Seconds (int/float) or a datetime (UTC if naive). Sets the Retry-After header.
Example::
return HttpResponseContentTooLarge(retry_after=300)
Source code in django_allresponses/responses.py
HttpResponseContinue
¶
Bases: HttpResponse
100 Continue.
Tell the client to keep sending the request body (used with Expect: 100-continue). The response has no body.
Note: Usually handled by the web server or proxy, not in Django views.
Source code in django_allresponses/responses.py
HttpResponseCreated
¶
Bases: HttpResponse
201 Created.
Use when you created a new resource. Pass the resource's URL as
location; it's sent as the Location header.
Args: location: URL of the new resource. content_location: Optional. URI of the representation (e.g. same as location). Sets Content-Location.
Example::
return HttpResponseCreated(
location=request.build_absolute_uri(obj.get_absolute_url())
)
Source code in django_allresponses/responses.py
HttpResponseExpectationFailed
¶
Bases: HttpResponse
417 Expectation Failed.
Use when you can't satisfy the request's Expect header (e.g. Expect: 100-continue but you won't accept the body).
Example::
return HttpResponseExpectationFailed()
Source code in django_allresponses/responses.py
HttpResponseForbidden
¶
Bases: HttpResponseForbidden
403 Forbidden.
Use when the user isn't -owed to do this (auth succeeded but permission denied). Use 404 instead if you want to hide that the resource exists.
Example::
return HttpResponseForbidden("You cannot edit this resource")
Source code in django_allresponses/responses.py
HttpResponseFound
¶
Bases: HttpResponseRedirect
302 Found.
Temporary redirect to another URL. Browsers may change POST to GET; use 307 if you need the method preserved.
Example::
return HttpResponseRedirect(new_url)
Source code in django_allresponses/responses.py
HttpResponseGatewayTimeout
¶
Bases: HttpResponse
504 Gateway Timeout.
Use when you're a gateway/proxy and the upstream didn't respond in time. Usually sent by the reverse proxy, not Django.
Source code in django_allresponses/responses.py
HttpResponseGone
¶
Bases: HttpResponseGone
410 Gone.
Use when the resource used to exist but is permanently gone (e.g. removed page). Tells clients to drop links. Use 404 if you're not sure.
Example::
return HttpResponseGone()
Source code in django_allresponses/responses.py
HttpResponseHttpVersionNotSupported
¶
Bases: HttpResponse
505 HTTP Version Not Supported.
Use when the request's HTTP version isn't supported. Usually handled by the web server, not Django.
Source code in django_allresponses/responses.py
HttpResponseInternalServerError
¶
Bases: HttpResponseServerError
500 Internal Server Error.
Use for unexpected server errors. Often sent automatically when your view raises; you can also return it explicitly for custom error pages.
Source code in django_allresponses/responses.py
HttpResponseLengthRequired
¶
Bases: HttpResponse
411 Length Required.
Use when the request body must include a Content-Length header and didn't. Client can retry with the header. Typically this will be implemented by the server, or maybe it's in some specialist middleware.
Example::
return HttpResponseLengthRequired()
Source code in django_allresponses/responses.py
HttpResponseMisdirectedRequest
¶
Bases: HttpResponse
421 Misdirected Request.
Use when this server isn't the right one for the request (e.g. wrong host for the URI). Client should try another connection. Proxies shouldn't send this.
Example::
return HttpResponseMisdirectedRequest()
Source code in django_allresponses/responses.py
HttpResponseMovedPermanently
¶
Bases: HttpResponsePermanentRedirect
301 Moved Permanently.
The resource has a new permanent URL. Browsers may cache this and change POST to GET on redirect; use 308 if you need the method kept. 308 ()
Example::
return HttpResponsePermanentRedirect(new_url)
Source code in django_allresponses/responses.py
HttpResponseMultipleChoices
¶
Bases: HttpResponse
300 Multiple Choices.
Use when the resource has several representations (e.g. languages). Send a list of options in the body or via Link headers; optional Location for a preferred choice.
Example::
return HttpResponseMultipleChoices(
"<ul><li><a href='/fr/'>French</a></li></ul>",
content_type="text/html",
)
Source code in django_allresponses/responses.py
HttpResponseNoContent
¶
Bases: HttpResponse
204 No Content.
Success, but no response body (e.g. after a delete or save). This class strips Content-Type and blocks you from setting content.
Example::
item.delete()
return HttpResponseNoContent()
Source code in django_allresponses/responses.py
HttpResponseNonAuthoritativeInformation
¶
Bases: HttpResponse
203 Non-Authoritative Information.
Use when a proxy modified the response (e.g. transcoding, anonymizing). Tells the client the body isn't the origin server's exact 200 response.
Example::
return HttpResponseNonAuthoritativeInformation(transformed_content)
Source code in django_allresponses/responses.py
HttpResponseNotAcceptable
¶
Bases: HttpResponse
406 Not Acceptable.
Use when you can't return a format the client will accept (Accept header). Problem is response format, not the request body (that's 415).
Example::
return HttpResponseNotAcceptable("Only application/json is available")
Source code in django_allresponses/responses.py
HttpResponseNotAllowed
¶
Bases: HttpResponse
405 Method Not Allowed.
Use when the HTTP method isn't allowed for this resource (e.g. POST to a read-only URL). Pass the list of allowed methods; this class sets the Allow header for you.
Args:
permitted_methods: Allowed methods, e.g. ["GET", "HEAD"].
Example::
return HttpResponseNotAllowed(["GET", "HEAD"])
Source code in django_allresponses/responses.py
HttpResponseNotFound
¶
Bases: HttpResponseNotFound
404 Not Found.
Use when the resource doesn't exist (or you don't want to reveal it). Use 410 Gone if it used to exist and is permanently removed.
Example::
return HttpResponseNotFound()
Source code in django_allresponses/responses.py
HttpResponseNotImplemented
¶
Bases: HttpResponse
501 Not Implemented.
Use when the server doesn't support this at all (e.g. unknown method). For a known method that's not allowed on this resource, use 405. Often sent by the web server; in Django you'll usually use 405.
Source code in django_allresponses/responses.py
HttpResponseNotModified
¶
Bases: HttpResponseNotModified
304 Not Modified.
Use when a conditional request (If-None-Match, If-Modified-Since) shows the client's copy is still valid. No body; this class strips Content-Type and blocks you from setting content.
Example::
return HttpResponseNotModified()
Source code in django_allresponses/responses.py
HttpResponseOK
¶
Bases: HttpResponse
200 OK.
The request succeeded. Use this for a normal response with a body. Use 204 when there's nothing to send in the body.
Example::
return HttpResponseOK("<p>Saved.</p>")
Source code in django_allresponses/responses.py
HttpResponsePartialContent
¶
Bases: HttpResponse
206 Partial Content.
Use for range requests (Range header). Send the byte range as body
and set a Content-Range header. Pass content_range as
(start, end, total) or a full string (e.g. "bytes 0-1023/2048").
Optional content_location sets Content-Location.
Args:
content: The partial byte range as body.
content_range: Optional. Either (start, end, total) for bytes, or
a full Content-Range string (e.g. "bytes 0-1023/2048").
content_location: Optional. URI of the representation. Sets
Content-Location.
Example::
return HttpResponsePartialContent(
partial_bytes,
content_range=(0, 1023, 2048),
)
Source code in django_allresponses/responses.py
HttpResponsePaymentRequired
¶
Bases: HttpResponse
402 Payment Required.
Use when the client must pay or subscribe before accessing the resource (e.g. quota exceeded, subscription required).
Example::
return HttpResponsePaymentRequired()
Source code in django_allresponses/responses.py
HttpResponsePermanentRedirect
¶
Bases: HttpResponse
308 Permanent Redirect.
Permanent redirect; the client MUST preserve the request method (POST stays POST). Use 301 when you're fine with browsers converting POST to GET and caching the redirect.
Example::
return HttpResponsePermanentRedirect308(redirect_to)
Source code in django_allresponses/responses.py
HttpResponsePreconditionFailed
¶
Bases: HttpResponse
412 Precondition Failed.
Use when a conditional header (If-Match, If-None-Match, If-Unmodified-Since) didn't match the current resource state. Typically, this will only be implemented in some specialist middleware.
Example::
return HttpResponsePreconditionFailed()
Source code in django_allresponses/responses.py
HttpResponseProxyAuthenticationRequired
¶
Bases: HttpResponse
407 Proxy Authentication Required.
Like 401 but for proxy auth. Set Proxy-Authenticate; client retries with Proxy-Authorization.
Example::
response = HttpResponseProxyAuthenticationRequired()
response["Proxy-Authenticate"] = 'Basic realm="Proxy"'
return response
Source code in django_allresponses/responses.py
HttpResponseRangeNotSatisfiable
¶
Bases: HttpResponse
416 Range Not Satisfiable.
Use when the Range header can't be satisfied. Pass total_length
to set Content-Range (e.g. bytes */47022). For non-byte range
units, set Content-Range manually.
Args:
total_length: Optional. Full length of the selected representation
in bytes. Sets Content-Range: bytes */<total_length>.
Example::
return HttpResponseRangeNotSatisfiable(total_length=resource_size)
Source code in django_allresponses/responses.py
HttpResponseRequestTimeout
¶
Bases: HttpResponse
408 Request Timeout.
Use when the client took too long to send the request (e.g. body
never arrived). Client can retry. Optionally pass retry_after
(seconds or datetime) to set Retry-After.
Args: retry_after: Optional. Seconds (int/float) or a datetime (UTC if naive). Sets the Retry-After header.
Example::
return HttpResponseRequestTimeout(retry_after=60)
Source code in django_allresponses/responses.py
HttpResponseResetContent
¶
Bases: HttpResponse
205 Reset Content.
Success; tell the client to reset the form/view so the user can enter again (e.g. after submitting a form). No body allowed; this class enforces that like 204.
Example::
return HttpResponseResetContent()
Source code in django_allresponses/responses.py
HttpResponseSeeOther
¶
Bases: HttpResponse
303 See Other.
Redirect the client to another URL with a GET request (e.g. after POST). The response to the new URL is the result of the request. Use 302 for a generic temporary redirect.
Example::
return HttpResponseSeeOther(new_url)
Source code in django_allresponses/responses.py
HttpResponseServiceUnavailable
¶
Bases: HttpResponse
503 Service Unavailable.
Use when you're temporarily unable to handle the request (overload,
maintenance). Optionally pass retry_after (seconds or a datetime)
and this class sets the Retry-After header.
Args: retry_after: Optional. Seconds (int/float) or a datetime (UTC if naive). Sets the Retry-After header.
Example::
return HttpResponseServiceUnavailable(retry_after=120)
Source code in django_allresponses/responses.py
HttpResponseSwitchingProtocols
¶
Bases: HttpResponse
101 Switching Protocols.
Tell the client you're switching protocol on this connection (e.g. to
WebSocket). Pass upgrade to set the Upgrade header (and
Connection: Upgrade).
Args:
upgrade: Protocol name(s), e.g. "websocket" or
["HTTP/3.0", "websocket"]. Sets Upgrade and Connection headers.
Note: Usually done by the web server or reverse proxy, not in Django.
Source code in django_allresponses/responses.py
HttpResponseTemporaryRedirect
¶
Bases: HttpResponse
307 Temporary Redirect.
Temporary redirect; the client MUST preserve the request method (POST stays POST). Use 302 when you're fine with browsers converting POST to GET.
Example::
return HttpResponseTemporaryRedirect(redirect_to)
Source code in django_allresponses/responses.py
HttpResponseUnauthorized
¶
Bases: HttpResponse
401 Unauthorized.
Use when the client must authenticate (missing or invalid credentials). You MUST send a WWW-Authenticate header; the client may retry with Authorization.
Example::
response = HttpResponseUnauthorized()
response["WWW-Authenticate"] = 'Basic realm="API"'
return response
Source code in django_allresponses/responses.py
HttpResponseUnprocessableContent
¶
Bases: HttpResponse
422 Unprocessable Content.
Use when the request body is valid (not 415) but you can't process it (e.g. validation failed, semantic error). Common in REST APIs to separate from 400 syntax errors.
Example::
return HttpResponseUnprocessableContent(
json.dumps({"errors": validation_errors}),
content_type="application/json",
)
Source code in django_allresponses/responses.py
HttpResponseUnsupportedMediaType
¶
Bases: HttpResponse
415 Unsupported Media Type.
Use when the request body is in a format you don't support (Content-Type or content). That's request body; for response format the client accepts, use 406.
Example::
return HttpResponseUnsupportedMediaType()
Source code in django_allresponses/responses.py
HttpResponseUpgradeRequired
¶
Bases: HttpResponse
426 Upgrade Required.
Use when the client must upgrade (e.g. to TLS). Pass upgrade
with the required protocol(s); this sets Upgrade and Connection:
Upgrade. You will typically not see this in Django views.
Args:
upgrade: Protocol name(s), e.g. "TLS/1.2" or
["HTTP/3.0", "websocket"]. Sets Upgrade and Connection headers.
Example::
return HttpResponseUpgradeRequired(upgrade="TLS/1.2")
Source code in django_allresponses/responses.py
HttpResponseUriTooLong
¶
Bases: HttpResponse
414 URI Too Long.
Use when the URL is too long. In practice the web server often enforces this before Django.
Example::
return HttpResponseUriTooLong()
Source code in django_allresponses/responses.py
HttpResponseUseProxy
¶
Bases: HttpResponse
305 Use Proxy.
Resource is only available via a proxy. Pass location with the
proxy URI. Deprecated; many clients ignore it. Prefer configuring
the proxy at the server level.
Args: location: Optional. URI of the proxy to use.
Source code in django_allresponses/responses.py
JsonResponseBadRequest
¶
JsonResponseConflict
¶
JsonResponseCreated
¶
Bases: _JsonResponseWithStatus
201 Created with JSON body and Location header.
Source code in django_allresponses/jsonresponses.py
JsonResponseForbidden
¶
JsonResponseNotAcceptable
¶
JsonResponseNotAllowed
¶
Bases: _JsonResponseWithStatus
405 Method Not Allowed with JSON body and Allow header.
Source code in django_allresponses/jsonresponses.py
JsonResponseNotFound
¶
JsonResponseOK
¶
JsonResponsePaymentRequired
¶
JsonResponseServerError
¶
JsonResponseServiceUnavailable
¶
JsonResponseUnauthorized
¶
JsonResponseUnprocessableContent
¶
Bases: _JsonResponseWithStatus
422 Unprocessable Content with JSON body (e.g. validation errors).
Source code in django_allresponses/jsonresponses.py
retry_after_value(retry_after)
¶
Return the Retry-After header value for the given delay.
Use with 408, 413, 503, or 3xx responses when the client may retry later.
Args: retry_after: Seconds (int/float) or a datetime (UTC if naive).
Returns: str: The header value (delay-seconds or HTTP-date).
Example::
response = HttpResponseServiceUnavailable()
response["Retry-After"] = retry_after_value(120)
Source code in django_allresponses/responses.py
set_content_location(response, uri)
¶
Set the Content-Location header on a response.
Use with 200, 201, 206, or 304 when the response body corresponds to a specific resource URI (e.g. after content negotiation).
Args: response: An HttpResponse instance. uri: Absolute or partial URI for the representation.