Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does HttpResponse(status=<code>) work in django?

I'm experimenting with HTTP error codes in django so I have a question about HttpResponse(status=<code>). For example, I want to send a HTTP error code 405, I have the following code:

def myview(request):
   if request.method == 'POST':
      ...
   else:
      return HttpResponse(status=405)

Also I have my template for this HTTP error code (405.html) and I put the following code line in urls.py

handler405 = 'handling_error.views.bad_method'

And my bad_method view is the following:

def bad_method(request):
    datos_template = {}
    return render(request, '405.html', datos_template, status=405)

I thought in this way Django redirect to correct template according to the HTTP error code, but it doesn't work, then:

Have I done incorrect something? How does HttpResponse(status=) work in django? What is the goal of sending a HTTP error code through HttpResponse(status=)?

Sorry, many questions :P

I hope someone can help me.

like image 961
hmrojas.p Avatar asked Jul 16 '15 18:07

hmrojas.p


1 Answers

HttpResponse(status=[code]) is just a way of sending the actual HTTP status code in the header of the response. It arrives at the client with that status_code, but does not do any changing of the data except for the HTTP header. You can pass any status code with a properly-working response, and it will still show up as before, but if you go into the browser's console you will see that it read it as a "405" page.

HTTP headers are simply transferred with each request and response for web server parsing and providing metadata/info to developers. Even 404 pages have content sent with them, to tell the user that there was a 404; if it didn't, the user would just get a blank page and have no idea what went wrong.

If you want to signify an error, you can take a look at these docs. Alternatively, you can use the HttpResponseRedirect (see here) option to direct to an error-view that serves a custom error response.

like image 169
Matthew R. Avatar answered Oct 07 '22 19:10

Matthew R.