Jon AtkinsonI'm a web developer and system administrator

Django's user_passes_test and generic views

Posted on 26th September 2008. Tagged as django, python, tips

Previously, I've often used a combination of django.contrib.auth and the login_required 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 is_staff and is_superuser fields.

It's trivial (and well documented) to use the user_passes_test 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), { ... }),
)

blog comments powered by Disqus

Twitter

About Me

Picture of Jon Atkinson

Jon Atkinson is a web developer, sysadmin and occasional business guy. He works in the north west of England.

Jon can be contacted at , or on freenode as JonA. Also available: twitter, LinkedIn and Github.

My Company

Testled logo

I'm a director of Testled, a company which provides bespoke web and mobile development for all kinds of businesses.

If you're interested in working with me, take a look, then contact me via Testled.