- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想让 Django 的 @login_required
装饰器测试 User 的特定字段是否已设置为 None 以外的值。 (添加的字段有 null = true 和默认值 None。)
新创建的 User 对象的字段值确实为 None,但是对 @login_required
的明显更改并没有在行为上产生明显的差异(我重新启动了 Gunicorn 以确保重新读取) . @login_required
View 在用户通过身份验证时呈现,即使添加的字段为 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
关于python - 如何在自定义 Pinax 安装上修改 Django 的 login_required 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37665971/
我是一名优秀的程序员,十分优秀!