Django: Custom Decorator with an Argument

March 29, 2010    decorators Django Python

Sometimes you want to be able to create a decorator for functions in Django but have the ability to pass in an argument into the decorator. I came across this when I wanted to switch from the require_login decorator to check if a user was in a certain group to see the function.

So the first thing I did was create a new directory in my project root called decorators and put a blank file there. My I cated an file with the following contents.

from functools import wraps

from django.contrib.auth.models import Group
from django.http import Http404

def group_required(groups=[]):    
    def decorator(func):
        def inner_decorator(request,*args, **kwargs):
            for group in groups:
                    if Group.objects.get(name=group) in request.user.groups.all():
                        return func(request, *args, **kwargs)

            raise Http404()

        return wraps(func)(inner_decorator)

    return decorator

So we can use it like this in our project

from decorators.auth import group_required

def show_index(request):

I decided to make it a list being passed in. The main reason was to make it was to pass in multiple groups that you might want to allow to be allowed in.

My version doesn’t do much error checking.. if you want a more updated version of this function checkout my githib project I’ve started to put all my custom decorators up and online

comments powered by Disqus