简体   繁体   中英

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 or @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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM