سؤال

I'm new to both web in general/django world. I've been raising Http404 for all my error cases (from my view). I think raising other than 404, such as 401, 402.. for different errors would be much nicer for me to detect what's gone wrong.

I found return HttpResponse(status=401) would do the job. But is this considered an acceptable practice? Should I not interfere with status code because each of them is supposed to mean something?

هل كانت مفيدة؟

المحلول

Each of the status codes has a specific meaning. See the List of HTTP status codes page on Wikipedia page for the meaning of each code.

You should choose an appropriate status code for each response. For example, you should only use 401 when the client is unauthorized. It's not a great idea to assign your own meanings to the status codes.

If you want to make it easier to detect the error, you could set a custom header instead:

response = HttpResponse()
response['My-App-Error'] = error_code
return response

نصائح أخرى

Yes you can subclass HttpResponse to handle different types of HTTP responses. More info here

For example, you can send HttpResponse with status code 403 as:

from django.http import HttpResponseBadRequest

def my_view(request):
    # ...


    return HttpResponseBadRequest('<h1>You are not authorized to view this page</h1>')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top