[英]Python decorator for Django views: Check for a particular setting in UserProfile
I'd like to write a decorator to use on views all over my site to first check if the logged in user's UserProfile has a particular setting. 我想编写一个装饰器,以便在我的网站上的所有视图上使用,以首先检查登录用户的UserProfile是否具有特定设置。 In my case it's user.get_profile.user_status and the value could be either "expired" or "active".
在我的情况下,它是user.get_profile.user_status,该值可以是“过期”或“活动”。 If the user_status = "expired" i want to redirect them to a billing account update page.
如果user_status =“ expired”,我想将其重定向到计费帐户更新页面。 If they are active, they can pass.
如果他们是活跃的,他们可以通过。
I'd like to be something like @must_be_active
or @paywall_check
. 我想成为
@must_be_active
或@paywall_check
类的东西。
Never wrote a decorator before. 以前从未写过装饰器。 Ideas on how best to get started?
关于如何最好地入门的想法?
First, read this http://docs.djangoproject.com/en/1.2/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test 首先,请阅读此http://docs.djangoproject.com/zh-CN/1.2/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test
It's actually simpler if you don't write a decorator. 如果您不编写装饰器,则实际上更简单。
from django.contrib.auth.decorators import user_passes_test
def must_be_active( user ):
if .... whatever ....
def paywall_check( user ):
if .... whatever ....
@user_passes_test(must_be_active)
def my_view(request):
do the work
@user_pass_test(paywall_check)
def another_view(request):
do the work
Short direct example 简短的直接示例
http://www.djangofoo.com/tag/custom-decorator http://www.djangofoo.com/tag/custom-decorator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.