2010-12-09 65 views
0

我想编写一个装饰器以在我的站点上的全部视图上使用,以首先检查登录用户的UserProfile是否具有特定设置。在我的情况下,它是user.get_profile.user_status,值可以是“过期”或“活动”。如果user_status =“已过期”,我想将它们重定向到结算帐户更新页面。如果他们活跃,他们可以通过。用于Django视图的Python装饰器:检查UserProfile中的特定设置

我想成为像@must_be_active@paywall_check

以前从未写过装饰器。关于如何最好地开始的想法?

回答

3

首先,请阅读本http://docs.djangoproject.com/en/1.2/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test

它实际上是简单的,如果你不写一个装饰。

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 
+0

这为我工作。但是,我并没有将这个技术应用到视图中,而是将其应用到了我的urls.py中,其中有类似的其他设置。把它们放在这里对我来说更有意义。在你回答之后,这篇相关的博客文章也很有帮助:http://jonatkinson.co.uk/djangos-user_passes_test-and-generic-views/ – Flowpoke 2010-12-09 21:46:49

相关问题