Writing Django Decorators

Posted: April 14th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: , | 1 Comment »

I had a situation today where I had to write a custom decorator for a Django app and thought I would post the code.

I first created a file called decorators.py and placed it in the project folder.

from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect

from functools import wraps

def access_required(permission):
    def decorator(func):
        def inner_decorator(request, *args, **kwargs):
            if permission == 'admin':
                if request.session['user_profile'].is_account_admin == 1:
                    return func(request, *args, **kwargs)
                else:
                    return HttpResponseRedirect(reverse('dashboard'))

        return wraps(func)(inner_decorator)

    return decorator

Then in my views I simply imported the decorator and added it to my view:

from webapp.decorators import access_required
@access_required('admin')
    def account_users(request):
        ...