Django admin 产生'WSGIRequest' object has no attribute 'user'的错误

django 版本1.8.升级到django2.0,

 

Django服务起来之后,登录admin后台时,抛出下面错误:

Django admin 产生'WSGIRequest' object has no attribute 'user'的错误

google了下,说是MIDDLEWARE配置的有问题,顺序应该保持参见(http://stackoverflow.com/questions/26576192/wsgirequest-object-has-no-attribute-user):

'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',

但是这样设置之后,依然没有解决。
我的1.8.3 MIDDLEWARE的配置是:

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware', )

实际上,这是Django版本的问题,1.10之前,中间件的key为MIDDLEWARE_CLASSES, 1.10之后,为MIDDLEWARE。所以在开发环境和其他环境的版本不一致时,要特别小心,会有坑。
改配置为django 2.0:(这个是django 2.1生成的,直接拷贝过来替换)

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

问题解决。
参考 http://www.ziqiangxuetang.com/django/django-middleware.html

05-11 11:22