group_required decorator

June 20, 2008 | In: development, django, python

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.

Bookmark and Share
  • ninjacipher
    Makes sense to me :) good call.
  • michiel_1981
    Hi,

    To make it less error prone move the return view line in a else statement.

    try:
    getting group
    except:
    return redirect
    else:
    return view

    This way if a Group.DoesNotExist is raised in your view function it won't be handled by the decorator.
    Which most likely shouldn't redirect.

    - Michiel
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001