HttpResponse如何(状态= <code>) work in django?

时间:2015-07-16 18:11:23

标签: python django http-error

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.

2 个答案:

答案 0 :(得分:4)

HttpResponse(status=[code])只是在响应标头中发送实际HTTP状态代码的一种方法。它使用该status_code到达客户端,但除了HTTP头之外不会更改任何数据。您可以使用正常工作的响应传递任何状态代码,它仍然会像以前一样显示,但如果您进入浏览器的控制台,您会看到它将其读作&#34; 405&#34 ;页。

HTTP标头随每个请求和响应一起传输,用于Web服务器解析并向开发人员提供元数据/信息。甚至404页面都有与他们一起发送的内容,告诉用户有404;如果它没有,用户只会得到一个空白页面,不知道出了什么问题。

如果您想表示错误,可以查看these docs。或者,您可以使用HttpResponseRedirectsee here)选项指向提供自定义错误响应的错误视图。

答案 1 :(得分:2)

Django允许您在urls.py中为handler400handler403handler404handler500指定error handlers。它不支持handler405

请注意,您可以返回任何状态的http响应,Django会将该响应返回给用户,它不会调用该状态代码的处理程序。

引发异常时会调用错误处理程序。例如,如果在视图中引发Http404,Django将调用handler404视图。