Django Wagtail Middleware启动错误:status_code未在响应中定义

时间:2017-05-29 15:52:46

标签: python django wagtail django-middleware

我正在将项目升级到Django 1.11。我重写了一个似乎正在运行的自定义网站中间件;但是,我不确定它是不会导致下游问题。这个自定义中间件是在Django和Wagtail的中间件之后调用的。但是,我得到的错误来自Wagtail的重定向中间件:

'NoneType' object has no attribute 'status_code'

以下是完整的跟踪:

Traceback (most recent call last):
  File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/utils/deprecation.py", line 142, in __call__
    response = self.process_response(request, response)
  File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailredirects/middleware.py", line 30, in process_response
    if response.status_code != 404:
AttributeError: 'NoneType' object has no attribute 'status_code'

以下是来自Wagtail的中间件代码导致错误;我注意到它正在使用弃用的Mixin:

# Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py
class RedirectMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        # No need to check for a redirect for non-404 responses.
        if response.status_code != 404: ...
            return response
        # If a middleware before `SiteMiddleware` returned a response the
        # `site` attribute was never set, ref #2120
        if not hasattr(request, 'site'):
            return response

有没有人遇到过这个?

2 个答案:

答案 0 :(得分:0)

我明白了 - 这是我的中间件。在响应(中间件的后半部分)上,我从return None中的旧式中间件process_request()获得__call__

# BROKEN - RETURNS None
def __call__(self, request):
    if request.user.is_authenticated():
        # If they're already auth'd, don't bother checking.
        return None

中间件类对象需要返回响应:

# FIXED - RETURNS self.get_response(request)
def __call__(self, request):
    if request.user.is_authenticated():
        # If they're already auth'd, don't bother checking.
        return self.get_response(request)

如果遇到此错误,响应周期中的先前中间件(中间件在MIDDLEWARE[]报告错误之前列出的中间件)将成为罪魁祸首!祝你好运。

答案 1 :(得分:0)

我在这里找到了答案,为我解决了这个问题:https://stackoverflow.com/a/47205733/1518734

您的404处理程序必须返回带有status_code = 404的响应,否则Wagtail重定向中间件将无法工作。