如何在自定义 Pinax 安装上修改 Django 的 login_required 装饰器?

How can I modify Django's login_required decorator on a custom Pinax installation?

我想让 Django 的 @login_required 装饰器测试用户的特定字段是否已设置为 None 以外的内容。 (添加的字段有 null = true 和默认值 None。)

新创建的 User 对象的字段值确实为 None,但是对 @login_required 的明显更改并没有在行为上产生明显的差异(我重新启动了 Gunicorn 以确保一个新的读)。 @login_required 如果用户经过身份验证,将呈现视图,即使添加的字段是 None。

现在的,稍有改动@login_required是:

def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.foo != None,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

原始 lambda 在 u.is_authenticated()

我从你的代码中看出,你确实遇到了user_passes_test,这实际上是你应该使用的,而不是直接修改login_required的源代码。

user_passes_test() takes a required argument: a callable that takes a User object and returns True if the user is allowed to view the page. Note that user_passes_test() does not automatically check that the User is not anonymous.

您只需创建一个函数来确保满足您的条件。这确保一切都保留在您的代码库中(对 django 的更新不会破坏您的应用程序)并使其更容易调试。

你的测试函数可能是。

def is_foo(user):
   if user.is_authenticated() and user.foo :
       return True