Request.user 在 settings.py 中使用时没有属性用户

Request.user has no attribute user when used in settings.py

当我尝试在我的 settings.py 文件中使用它时,

request.user 生成一个 AttributeError: 'WSGIRequest' object has no attribute 'user' 错误。我做错了什么吗?

Settings.py:

def show_toolbar(request):
    if DEBUG:
        return True
    #if not request.is_ajax() and request.user and request.user.UserSettings.debugger:
    #    return True
    return False
DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': 'acacia2.settings.show_toolbar',
}

如果没有看到您的中间件列表,我不能肯定地说,但这就是我怀疑正在发生的事情:

为什么不起作用

  • user 属性由 contrib.auth 中间件设置。
  • 您在上面定义的函数被 django-debug-toolbar 中间件。

如果你的 django-debug-toolbar 中间件在你的 MIDDLEWARE 设置中定义的中间件列表中的 contrib.auth 中间件之前,那么当请求到达你的 debug-toolbar 中间件时它不会'尚未在其上设置用户对象。因此你的错误('WSGIRequest' object has no attribute 'user')。

如何修复

确保 django-debug-toolbar 中间件在 auth 中间件之后,例如:

MIDDLEWARE = [
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    ...

]