NinjaCipher:-*-:ro60

Archive for June, 2008

group_required decorator

Friday, June 20th, 2008

Here is a decorator that I came up with to augment the already available login_required and permission_required decorators. This one takes a group name and makes sure the logged in user is a part of it.

def group_required(group_name, login_url='/accounts/login/'):
    def wrap(view_func):
        def in_group(request, *args, **kwargs):
            from django.contrib.auth.models import Group
            try:
                group = request.user.groups.get(name=group_name)
            except Group.DoesNotExist:
                from django.http import HttpResponseRedirect
                return HttpResponseRedirect(login_url)
            else:
                return view_func(request, *args, **kwargs)

        return in_group
    return wrap

to use

@group_required('groupies')
def index(request):
   ...

I’m posting this with a disclaimer up front. Every time I post what I think is a clever snippet someone always tells me that I am reinventing the wheel and it already exists in django. So if this is another case of me being tragically uninformed then please let me know as I would most likely use the official way instead.