Django 1.5.1 login_required装饰器没有捕获未经身​​份验证的用户

时间:2013-09-14 06:44:53

标签: python django login-required

我有一个非常典型的view / login_required装饰器实现,并且有人向我报告,有时候每天两次,QA团队会遇到这个错误:

ERROR: AttributeError at /plan/reviewplan/1702/ 'WSGIRequest' object has no 
attribute 'user' Request Method: GET Request URL: 
http://<ip>/plan/reviewplan/1702/ Django Version: 1.5.1

Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 187. 
response = middleware_method(request, response) 
File "/usr/local/lib/python2.6/dist-packages/debug_toolbar/panels/template.py" in process_response 118. pformat(k(self.request))) for k in get_standard_processors() 
File "/opt/ion/iondb/rundb/context_processors.py" in base_context_processor 25. 
if request.user: Exception Type: AttributeError at /plan/reviewplan/1702/ 
Exception Value: 'WSGIRequest' object has no attribute 'user' 

我检查过,视图确实有一个login_required装饰器。在其他使用login_required修饰的视图中也会报告。

观点的回报是:

return render_to_response("template.html", context_instance=ctx, mimetype="text/html")

仅供参考:ctx实例存储在会话中,并且经常在视图调用之间更新。我继承了这个设计,我对此无能为力。处理此问题的函数是:

def _create_context_from_session(request, next_step_name):
    ctxd = request.session['saved_plan']
    ctxd['helper'] = request.session['plan_step_helper']
    ctxd['step'] = None
    if next_step_name in ctxd['helper'].steps:
        ctxd['step'] = ctxd['helper'].steps[next_step_name]
    context = RequestContext(request, ctxd)
    return context

1 个答案:

答案 0 :(得分:0)

也许存储在会话中的上下文变量存储了一个旧的请求实例(没有用户属性)?也许修改返回的上下文以包含当前请求,如下所示:

def _create_context_from_session(request, next_step_name):
    ctxd = request.session['saved_plan']
    ctxd['request'] = request  # Add this line.
    ...

您的"django.contrib.auth.context_processors.auth"中有TEMPLATE_CONTEXT_PROCESSORS吗?

似乎也启用了调试工具栏。禁用调试工具栏时是否存在问题?

同时

调试工具栏正在其中间件中执行模板上下文处理器,并且您的一个上下文处理器尝试访问request.user

您可以修改此追溯中提到的行:

File "/opt/ion/iondb/rundb/context_processors.py" in base_context_processor 25. 
if request.user: Exception Type: AttributeError at /plan/reviewplan/1702/ 

而不是if request.user:文件中if hasattr(request, 'user'): /opt/ion/iondb/rundb/context_processors.py

"/opt/ion/iondb/rundb/context_processors.py"上下文处理器是否在"django.contrib.auth.context_processors.auth"之后执行?上下文处理器的执行顺序由TEMPLATE_CONTEXT_PROCESSORS设置定义。