这是对 Yuji 答案的改进,它提供了堆栈跟踪、更多说明(对于我们 django 新手而言)并且更简单。
将此代码放在应用程序某处的文件中,例如PROJECT_ROOT/MAIN_APP/middleware/exceptions.py,并确保在同一目录中有一个空的__init__.py。
import traceback
from django.http import HttpResponse
class PlainExceptionsMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse(traceback.format_exc(exception), content_type="text/plain", status=500)
现在编辑您的settings.py 并找到MIDDLEWARE_CLASSES = (。添加另一个条目,如下所示:
MIDDLEWARE_CLASSES = (
# (all the previous entries)
# Plain text exception pages.
'MAIN_APP.middleware.exceptions.PlainExceptionsMiddleware',
)
重新启动 django,一切顺利!
用户代理感知格式。
如果您像我一样开发由 django 支持的应用程序和网站,您可能希望向应用程序显示纯文本错误页面,并向浏览器显示格式良好的错误页面。一个简单的方法是检查用户代理:
import traceback
from django.http import HttpResponse
class PlainExceptionsMiddleware(object):
def process_exception(self, request, exception):
if "HTTP_USER_AGENT" in request.META and "chrome" in request.META["HTTP_USER_AGENT"].lower():
return
return HttpResponse(traceback.format_exc(exception), content_type="text/plain", status=500)