[英]Django HTTP 500 Error
I am creating a custom HTTP 500 error template. 我正在创建自定义HTTP 500错误模板。 Why is it Django shows it when i raise an exception and not when I return HttpResponseServerError (I just get the default browser 500 error)?
为什么Django在我引发异常时显示它而不是在我返回HttpResponseServerError时(我只是得到默认的浏览器500错误)? I find this behaviour strange...
我觉得这个行为很奇怪......
The HttpResponseServerError
inherits from HttpResponse
and is actually quite simple: HttpResponseServerError
继承自HttpResponse
,实际上非常简单:
class HttpResponseServerError(HttpResponse):
status_code = 500
So let's look at the HttpResponse
constructor: 那么让我们看看
HttpResponse
构造函数:
def __init__(self, content='', *args, **kwargs):
super(HttpResponse, self).__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
As you can see by default content
is empty. 正如您所看到的,默认情况下
content
为空。
Now, let's take a look at how it is called by Django itself (an excerpt from django.views.defaults): 现在,我们来看看Django本身如何调用它(摘自django.views.defaults):
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error (500)</h1>')
return http.HttpResponseServerError(template.render(Context({})))
As you can see when you produce a server error, the template named 500.html is used, but when you simply return HttpResponseServerError
the content is empty and the browser falls back to it's default page. 正如您在生成服务器错误时所看到的那样,使用名为500.html的模板,但是当您只返回
HttpResponseServerError
,内容为空,浏览器将回退到其默认页面。
Put this below in the urls.py. 把这个放在urls.py中。
#handle the errors
from django.utils.functional import curry
from django.views.defaults import *
handler500 = curry(server_error, template_name='500.html')
Put 500.html in your templates. 将500.html放入模板中。 Just as simple like that.
就像那样简单。
Have you tried with another browser ? 你试过用另一个浏览器吗? Is your custom error page larger than 512 bytes ?
您的自定义错误页面是否大于512字节? It seems some browsers (including Chrome) replace errors page with their own when the server's answer is shorter than 512 bytes.
当服务器的答案短于512字节时,似乎某些浏览器(包括Chrome)会将错误页面替换为自己的页面。
As of Django 2+ all you need to do is put the corresponding error templates in your base templates folder. 从Django 2+开始,您需要做的就是将相应的错误模板放在基本模板文件夹中。 Django will automatically render them before rendering the default.
Django会在渲染默认值之前自动渲染它们。
https://docs.djangoproject.com/en/2.0/ref/views/#error-views https://docs.djangoproject.com/en/2.0/ref/views/#error-views
In your case just drop your template '500.html' (or '404.html') into /templates 在您的情况下,只需将模板“500.html”(或“404.html”)放入/ templates
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.