我正在运行我的Django代码,但收到此错误
AttributeError: 'WSGIRequest' object has no attribute 'user'
我的Django版本是1.8.2,这是我的中间件类setting.py
MIDDLEWARE_CLASSES = (
'khxia.middlewares.PeeweeConnectionMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'subdomains.middleware.SubdomainURLRoutingMiddleware',
'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',
'referral.middlewares.ReferralRecordMiddleware',
'common.middlewares.ExceptionMiddleware',
)
这是我的完整追溯
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/base.py", line 268, in handle_uncaught_exception
return callback(request, **param_dict)
File "/Users/motion/Documents/GitHub/khx2/khxia/home/views.py", line 68, in server_error
res = render(request, 'home/500.html')
File "/Users/motion/Documents/GitHub/khx2/khxia/common/shortcuts.py", line 40, in render
if request.user.is_authenticated():
AttributeError: 'WSGIRequest' object has no attribute 'user'
views.py的第68行是:
def server_error(request):
res = render(request, 'home/500.html')
res.status_code = 500
return res
渲染功能显示为:
def render(request, template_name, dictionary=None):
"""
:param request: Django request object
:param template_name: template name
:param dictionary: parameter of dictionary
"""
dictionary = dictionary or {}
dictionary.update({
'settings': settings,
'DEBUG': settings.DEBUG,
'server_time': int(time.time()),
})
if request.user.is_authenticated():
dictionary['user_hashid'] = hashid.encode(request.user.id)
temp = template_name.replace('.html', '').split('/')
if len(temp) == 1:
module = 'v{name}'.format(name=temp[0].capitalize())
else:
name = ''.join([t.capitalize() for t in temp])
module = 'v{name}'.format(name=name)
dictionary['load_module'] = module
return django_render(
request,
template_name,
dictionary
)
答案 0 :(得分:3)
这是因为您放置中间件的顺序。
AuthenticationMiddleware将request.user添加到WSGI Request对象。
地点
'khxia.middlewares.PeeweeConnectionMiddleware',
AuthenticationMiddleware之后的这个中间件,或者作为最后的中间件