permission_required with multiple permissions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test

def any_permission_required(*args):
    """
    A decorator which checks user has any of the given permissions.
    permission required can not be used in its place as that takes only a
    single permission.
    """
    def test_func(user):
        for perm in args:
            if user.has_perm(perm):
                return True
        return False
    return user_passes_test(test_func)
        
#permission_required for comparisions
def permission_required(perm, login_url=None):
    """
    Decorator for views that checks whether a user has a particular permission
    enabled, redirecting to the log-in page if necessary.
    """
    return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)

More like this

  1. Auth decorators with 403 by Magus 5 years, 12 months ago
  2. Permission Required Middleware by mattgrayson 4 years, 5 months ago
  3. View Permission Decorator Helper by jgeewax 4 years, 10 months ago
  4. group_required decorator by msanders 3 years, 8 months ago
  5. Support for permissions for anonymous users in django ModelBackend by jb 1 year, 6 months ago

Comments

ryankask1 (on January 26, 2012):

This can be simplified in Python 2.5 and above:

def any_permission_required(*perms):
    return user_passes_test(lambda u: any(u.has_perm(perm) for perm in perms))

#

(Forgotten your password?)