NinjaCipher:-*-:ro60

group_required decorator

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.

Del.icio.us Digg BlinkList Furl Ma.gnolia Reddit Spurl

3 Responses to “group_required decorator”

  1. michiel_1981 Says:

    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

  2. mattd Says:

    Makes sense to me :) good call.

  3. Recent URLs tagged Decorator - Urlrecorder Says:

    [...] Recent public urls tagged “decorator” → group_required decorator [...]

Leave a Reply

You must be logged in to post a comment.