我喜欢在脚本中的不同位置引发 404 错误消息,例如:Http404("some error msg: %s"%msg)
因此,在我的 urls.py 中我包括:
handler404 = Custom404.as_view()
任何人都可以告诉我应该如何处理我的观点中的错误。我对 Django 还很陌生,所以一个例子会有很大帮助。
非常感谢。
最佳答案
通常 404 错误中不应该有任何自定义消息,但如果您想实现它,可以使用 django 中间件来实现。
中间件
from django.http import Http404, HttpResponse
class Custom404Middleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http404):
# implement your custom logic. You can send
# http response with any template or message
# here. unicode(exception) will give the custom
# error message that was passed.
msg = unicode(exception)
return HttpResponse(msg, status=404)
中间件设置
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'college.middleware.Custom404Middleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
这样就可以了。如果我做错了什么,请纠正我。希望这会有所帮助。
关于Django 通过消息引发 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367374/