Password protecting a Django site

Bit of a techy one, but I thought if I spend ten minutes writing this down it will, in the future, save me five minutes of re-Googling. Hmm. Anyway, if you want to add htaccess-style simple password protection to a Django website, here’s one way to do it fairly painlessly.

UPDATE: Since writing this I’ve found an easier way: use django-lockdown. Once you’ve pip installed the code (or however you prefer to do it), you have a number of options, such as protecting individual views or sites. But to just protect everything, with a password, add this to your settings:

INSTALLED_APPS += ('lockdown', )
MIDDLEWARE_CLASSES += ('lockdown.middleware.LockdownMiddleware', )
LOCKDOWN_PASSWORDS = ('yourpasswordhere', )
LOCKDOWN_FORM = 'lockdown.forms.LockdownForm'

Obviously, setting your preferred password(s) in there. That should do the job (worked for me with Django 1.4). (21 January 2013)


The django-password-required app is designed for this kind of thing. You set a password in your settings file and add a decorator to any views you want protected. Visitors to those pages are then presented with a very simple (not pretty) form. Seems to work.

But that’s a bit of a pain if you want to protect your whole website — decorating every view. Another way would be to add the decorator in your urls.py. Hopefully, your main urls.py has something like this:

urlpatterns = patterns('',
    (r'^', include('appname.urls')),
)

This gives us one point at which to affect all of the site’s URLs. It’s not too tricky to apply a decorator to a Django url rule, but I don’t think there’s a way to apply it when including another url file. So you need the django-decorator-include app. With this installed we can change the above to this:

from password_required.decorators import password_required
from decorator_include import decorator_include

urlpatterns = patterns('',
    (r'^', decorator_include(password_required, 'appname.urls')),
)

And there we go, your whole site is password protected. A bit more of a faff than htaccess, but sometimes that’s not possible.

24 Jan 2012 at Twitter

  • 5:57pm: On ‘I LOVE 2012 WEEK 3’: Stuart Maconie remembers that 360º Shard photo and Noddy Holder recalls the NY Times article about groupthink.