【问题标题】:Django display 404 on missing templateDjango 在缺少模板上显示 404
【发布时间】:2011-08-21 01:19:28
【问题描述】:

我有一个网站,其中一些页面是手动编辑的。当其中一个模板丢失时,仅表示该页面不存在,因此我想显示错误 404。

相反,我得到了一个异常 TemplateDoesNotExist。

有没有办法告诉 Django 在找不到模板时显示错误 404?

【问题讨论】:

    标签: django http-status-code-404


    【解决方案1】:

    我不以为然,但是如果您在设置中设置 DEBUG=False,那么您不会在每个错误(包括 TemplateNotFound)上得到 404 吗?

    【讨论】:

    • 我想是的,但我需要这个来测试。
    • 这个答案不正确。对于错误,默认的 Django 行为是运行 server_error 视图,将呈现 500.html 模板并返回错误代码为 500 的页面。请参阅 docs.djangoproject.com/en/dev/topics/http/views/…
    【解决方案2】:

    如果您希望网站上的所有视图都具有这种行为,您可能需要使用 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)
    

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

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

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

    【讨论】:

      【解决方案3】:

      将响应的返回放在视图中(或任何呈现模板的地方)中的 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
      

      【讨论】:

      • 需要导入异常:from django.template import TemplateDoesNotExist.
      • 感谢您的加入。我忘记了从哪里导入异常,因为无法检查。编辑了答案。
      • 是的,我知道我可以做到这一点,但在所有观点中它都变成了一些样板。我希望有一种全球性的方式来做到这一点。
      • 如果你想避免样板,定义一个函数my_render_to_response,它封装了try..except块。然后在您的视图中使用my_render_to_response 而不是 render_to_response。
      猜你喜欢
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      相关资源
      最近更新 更多