Django - Restrict View Access by Group Membership

Feb 22, 2011
import string
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
try: from functools import wraps
except ImportError: from django.utils.functional import wraps # Python 2.4 fallback.
from django.utils.decorators import available_attrs

def user_in_group(group_name, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            u = request.user
            if u.is_staff or (u.is_authenticated() and
                (group_name in [string.lower(g.name) for g in u.groups.all()])):
                return view_func(request, *args, **kwargs)
            messages.add_message(request, messages.ERROR, "You are not a member of the %s group." % group_name)
            return HttpResponseRedirect("/")
        return _wrapped_view
    return decorator