How do I return custom response/status code in Django?
Asked Answered
H

1

5

I want to return status code different from 100 <= self.status_code <= 599, as written in Django's HttpResponseBase class. Is there are any easy way to bypass this restriction?

Hyperopia answered 8/9, 2020 at 21:52 Comment(1)
The HTTP codes have ranges, for example 100-199 is information, 200-299 is success, 300-399 redirection, etc. So it does not make much sense to return a status code outside this range. Especially since a browser will typically for example redirect in case of a 301/302.Fraser
F
9

You can, if you really want, patch the .status_code attribute. For example with:

from django.http import HttpResponse

def some_view(request):
    response = HttpResponse('some data')
    response.status_code = 754  # sample status code
    return response

But it does not make much sense to specify a HTTP status code [wiki] outside the 100-599 range, since these are subdivided into subranges that specify in what case to return what status code.

Fraser answered 8/9, 2020 at 22:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.