And*_*rea 9 django http-status-code-404
我有一个网站,手工编辑一些页面.当缺少其中一个模板时,它只是意味着页面不存在,所以我想显示错误404.
相反,我得到一个例外TemplateDoesNotExist.
有没有办法告诉Django在找不到模板时显示错误404?
Ala*_*air 13
如果您希望对您网站上的所有视图使用此行为,则可能需要使用process_exception
方法编写自己的中间件.
from django.template import TemplateDoesNotExist
from django.views.defaults import page_not_found
class TemplateDoesNotExistMiddleware(object):
"""
If this is enabled, the middleware will catch
TemplateDoesNotExist exceptions, and return a 404
response.
"""
def process_exception(self, request, exception):
if isinstance(exception, TemplateDoesNotExist):
return page_not_found(request)
Run Code Online (Sandbox Code Playgroud)
如果您已经定义了自己的handler404
,则需要在page_not_found
上面替换.我不能立即确定如何将字符串handler404
转换为中间件所需的可调用内容.
为了使您的中间件,将其添加到MIDDLEWARE_CLASSES
在settings.py
.小心添加它的位置.标准的Django中间件警告适用:
同样,中间件在响应阶段以相反的顺序运行,其中包括process_exception.如果异常中间件返回响应,则根本不会调用该中间件之上的中间件类.
在try-except块中将响应的返回放在视图中(或者在模板呈现时):
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import TemplateDoesNotExist
def the_view(request):
...
try:
return render_to_response(...)
except TemplateDoesNotExist:
raise Http404
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3050 次 |
最近记录: |