A simple extension of the user_passes_test decorator:
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.
Checks is_active and allows superusers to pass regardless of group
membership.
"""
def in_group(u):
return u.is_active and (u.is_superuser or bool(u.groups.filter(name__in=group_names)))
return user_passes_test(in_group)
Thanks to Michael Sanders for his comment. I revised the decorator to check is_active and also to allow superusers to pass.
#1 by Michael Sanders on September 10, 2009 - 5:09 am
I have extended your code to first check that the user is logged in before testing group membership. Please see:
http://www.djangosnippets.org/snippets/1703/
#2 by David Chandek-Stark on October 12, 2009 - 9:50 am
Technically, that’s not necessary because u.groups.all() is an empty list if u is an AnonymousUser — the only case under which u.is_authenticated() returns False. I agree, however, that allowing superusers to pass the test (as you have also added) is probably expected behavior in this case.