Login

group_required decorator

Author:
msanders
Posted:
August 27, 2009
Language:
Python
Version:
1.1
Tags:
decorator auth groups
Score:
3 (after 3 ratings)

This snippet provides a @group_required decorator. You can pass in multiple groups, for example:

@group_required('admins','editors')
def myview(request, id):
...

Note: the decorator is based on the snippet here but extends it checking first that the user is logged in before testing for group membership - user_passes_test does not check for this by default.

It is important to check that the user is first logged in, as anonymous users trigger an AttributeError when the groups filter is executed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django.contrib.auth.decorators import user_passes_test

def group_required(*group_names):
    """Requires user membership in at least one of the groups passed in."""
    def in_groups(u):
        if u.is_authenticated():
            if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
                return True
        return False
    return user_passes_test(in_groups)

More like this

  1. User groups template tag by davea 3 years, 10 months ago
  2. HTTP basic auth decorator by bthomas 6 years, 7 months ago
  3. User groups template tag by hijinks 6 years, 2 months ago
  4. anonymous_required decorator by yetty 2 years, 1 month ago
  5. is_staff decorator by munhitsu 7 years ago

Comments

mapcuk (on February 25, 2010):

For using it in urls.py shoud write

urlpatterns = patterns('',
    url(r'^$',
        group_required(['root', 'manager'])(views.admin),
        name='admin'),
...

#

bradbeattie (on May 8, 2013):

Avoid a potentially unnecessary database hit by swapping the position of is_superuser and the groups.filter.

#

Please login first before commenting.