我需要将django'import error'重定向到自定义错误页面。除导入错误之外的所有其他错误都会重定向到自定义错误页面
已经在DEBUG = False 浏览器中显示的错误是
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "/usr/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 272, in __call__
response = self.get_response(request)
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 214, in handle_uncaught_exception
if resolver.urlconf_module is None:
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 274, in _get_urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/project/backup/project/hg/rel0129/hg/src/customer_/../customer_/hg/urls.py", line 4, in <module>
from lostpassword.views import recaptcha, reset
File "/project/backup/project/hg/rel0129/hg/../customer_/hg/lostpassword/views.py", line 12, in <module>
from hg.utils.common import __render, __redirect
hg/utils/common.py", line 15, in <module>
from urllibwrapper import URLClient, ClientResponse
ImportError: No module named urlwrapper
错误需要重定向到自定义错误页面
提前致谢
答案 0 :(得分:2)
当出现导入错误时,Django 已经显示错误页面;显示的错误页面取决于DEBUG
的值。
如果DEBUG
设置为True
,则会显示回溯和一些调试信息。
如果DEBUG
为False
,Django会显示默认的500错误页面。您可以通过在模板目录的根目录中提供500.html
页面,或在根URLConf中提供handler500
字符串来设置自定义500错误响应。
请参阅500 error view documentation。
但是,项目中的导入错误可能会阻止正确配置Django,并且找不到自定义500错误处理程序。有一个“太破碎”的事情,早期的进口例外就是这种情况。该异常然后完全绕过Django错误处理并转而降低到WSGI服务器级别。
在这种情况下,提供的DEBUG
设置为False
,会向用户显示默认的500错误消息,一条简单的短信:
发生服务器错误。请联系管理员。
请注意,即使调试模式关闭,较早的 Django版本(1.4之前)内置服务器仍然可以显示导入异常的回溯,因为这些旧版本使用自己的简单HTTP服务器。
在这种情况下,您可以将Django服务器升级到1.4或更高版本,和/或不使用内置服务器。请使用正确的production deployment。
答案 1 :(得分:1)
要提出自定义错误页面,您需要定义模板,然后将以下内容添加到urls.py
:
handler500 = 'mysite.views.my_custom_error_view'
要查看更多内容(包括追溯 - 如果DEBUG = False
,则不建议)查看this answer至Django 500 message in custom template。
此server_error视图应该足以满足99%的Web应用程序,但是如果要覆盖视图,则可以在根URLconf中指定handler500,如下所示:
handler500 = 'mysite.views.my_custom_error_view'
在幕后,Django通过在根URLconf中查找
500
来确定handler500
视图,如果没有定义,则返回django.views.defaults.server_error
。有关
500
次观看的一件事:如果
DEBUG
设置为True
(在您的设置模块中),则永远不会使用您的500
视图,而是会显示回溯,并显示一些调试信息。