【问题标题】:Is it possible to render a template from middleware?是否可以从中间件呈现模板?
【发布时间】:2011-02-15 20:26:53
【问题描述】:

我有一个做一些处理的中间件。在某些情况下,它会引发异常,并且用户会看到我的 500.html 模板 - 正确响应 500 http 状态。

现在,在某些例外情况下,我想呈现与默认 500.html 不同的模板。是否有可能/如何实现?

【问题讨论】:

    标签: django django-templates render middleware


    【解决方案1】:

    您可以捕获这些异常并return a HttpResponse object 来呈现您的自定义模板。或者也许重定向也是合适的。

    【讨论】:

      【解决方案2】:

      中间件可能是一种解决方案:

      class MyExceptionMiddleware:
         def process_exception(self, request, exception):
      
           if isinstance(exception, CustomException):
             template = loader.get_template('Other500.html')
             context = RequestContext(request, {'message': 'Custom Message'})
             return HttpResponseForbidden(template.render(context))
      
           return None
      

      不要忘记在 settings.py 中注册中间件:

      MIDDLEWARE_CLASSES = (
          ....
          'app.middleware.MyExceptionMiddleware',
      

      【讨论】:

        【解决方案3】:

        是的……也不是。

        你可以渲染任何你想要的东西(你的网络服务器有一个很好的解释如何做到这一点),但是用户是否会看到这是他的选择 - 通过他的浏览器设置。您可能会渲染某些内容,但浏览器仍会显示标准错误页面。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 1970-01-01
          • 2017-08-19
          • 2020-09-12
          • 2016-02-03
          • 2014-12-19
          相关资源
          最近更新 更多