首页 > 解决方案 > 将 login_required 与 user_passes_test 结合使用时,Django 'User' 对象没有属性 'user'

问题描述

我正在尝试将自定义user_passes_testlogin_required装饰器结合起来。

这工作正常:

@login_required
@user_passes_test(profile_expired, "Main:profile_expired")
def home(request):
    return render(request, "Main/pages/home.html", {})

在 helpers.py 中

def profile_expired(user):
    if user.is_authenticated and user.profile.expiration_date is not None:
        return user.profile.expiration_date >= date.today()
    elif user.profile.expiration_date is None:
        return True
    return False

如果我访问/app/profile_expired返回 True,我将被重定向到/app/profile_expired.

但是,所有其他视图上的相同代码正在返回错误...

@login_required
@user_passes_test(profile_expired, "Main:profile_expired")
def another_view(request):
    # some code...
    return render(request, "Main/pages/another_page.html", context)

错误:

Traceback (most recent call last):
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view
    if test_func(request.user):
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view
    if test_func(request.user):
  File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\utils\functional.py", line 257, in inner
    return func(self._wrapped, *args)
AttributeError: 'User' object has no attribute 'user'

虽然home只有上面的代码,another_view(和所有其他视图)有更多代码......但是错误不能出现在视图内,因为我已经在其中放置了一个断点,启动了调试器,并且它们永远不会被触发。错误必须在其他地方。

我无法确定为什么会发生这种情况。任何想法?

标签: pythondjangodecoratordjango-authentication

解决方案


test_func 应该以 auser作为它的参数。

def profile_expired(user):
    return user.profile.expiry_date > date.today()

你还没有展示你的功能,但我怀疑你已经写了它来接受请求,然后使用request.user.

def profile_expired(request):
    return request.user.profile.expiry_date > date.today()

推荐阅读