Django在缺少的模板上显示404 [英] Django display 404 on missing template

查看:159
本文介绍了Django在缺少的模板上显示404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,其中的一些页面都是手工编辑的.如果缺少这些模板之一,则仅表示该页面不存在,因此我想显示错误404.

I have a website where some pages are edited by hand. When one of those templates is missing, it just means that the page is not present, so I would like to display an Error 404.

相反,我得到一个例外TemplateDoesNotExist.

Instead I get an exception TemplateDoesNotExist.

有没有一种方法可以告诉Django在找不到模板时显示错误404?

Is there a way to tell Django to display an error 404 whenever it does not find a template?

推荐答案

如果您希望网站上所有视图都具有这种行为,则可能需要使用

If you want this behaviour for all views on your site, you might want to write your own middleware with a process_exception method.

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)

如果您定义了自己的 handler404 ,则需要替换page_not_found以上.我不确定是否可以将字符串handler404转换为中间件所需的可调用对象.

If you have defined your own handler404 you would need to replace page_not_found above. I'm not immediately sure how you could convert the string handler404 into the callable required in the middleware..

要启用中间件,请将其添加到settings.py中的MIDDLEWARE_CLASSES.请注意添加位置.标准的Django中间件警告适用:

To enable your middleware, add it to MIDDLEWARE_CLASSES in settings.py. Be careful of the position where you add it. The standard Django middleware warning applies:

同样,中间件在响应阶段(包括process_exception)以相反的顺序运行.如果异常中间件返回响应,则根本不会调用该中间件之上的中间件类.

Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.

这篇关于Django在缺少的模板上显示404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆