Jon Atkinson

I'm a technologist, with a long and varied history in high-end technical delivery and infrastructure management. I'm particularly interested in managing software teams, rapid application development, and scalability challenges.

Django's user_passes_test and generic views

26th September 2008

Previously, I've often used a combination of django.contrib.auth and the loginrequired decorator as a simple way of controlling access to certain parts of an application. However, I'm working on a fairly complex application right now, which will grant access based on the isstaff and is_superuser fields.

It's trivial (and well documented) to use the userpassestest decorator in a view, but in my case I'm using generic views. This is not so well documented. Here is a basic example of how to do it:

from django.conf.urls.defaults import *
from django.contrib.auth.decorators import user_passes_test

staff_required = user_passes_test(lambda u: u.is_staff)
superuser_required = user_passes_test(lambda u: u.is_superuser)

urls = patterns('',
    (r'^staff_only/$', staff_required(generic.view.here), { ... }),
    (r'^super_only/$', superuser_required(generic.view.here), { ... }),