开发者

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. In my case it's user.get_profile.user_status and the value could be either "expired" or "active". If the user_status = "expired" i want to redirect them to a billing account update page. If they are active, they can pass.

I'd like to be something like @must_be_active o开发者_如何学Gor @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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜