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.

June 20th, 2008 at 2:54 pm
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
June 20th, 2008 at 6:27 pm
Makes sense to me
good call.
October 30th, 2008 at 12:01 am
[...] Recent public urls tagged “decorator” → group_required decorator [...]