2012-11-06

Enforcing Strong Passwords in Django Admin

After googling the subject for hours and getting nowhere I decided to turn to the #django channel on freenode. If you'd like to enforce a minimum password strength in the Django Admin app you're in the right place.

Generally, you'll want to follow the steps here. The final missing ingredients are two attributes to the UserAdmin class you won't find in the docs... .add_form and .change_password_form.
 
Thanks to mattmc on irc for pointing me in the right direction. The attributes appear to be undocumented, but are there if you know exactly where to look.  Like Mr. T I've got no more time for jibba-jabba.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import (UserCreationForm,
    AdminPasswordChangeForm)
from django.contrib.auth.models import User
from django.contrib import admin
from django.forms import ValidationError

# password enforcement:
class myUserCreationForm(UserCreationForm):
    def clean_password1(self):
        passwd = self.cleaned_data['password1']
        if passwd and len(passwd) < 6:
            raise ValidationError('password too short.')
        return passwd

class myAdminPasswordChangeForm(AdminPasswordChangeForm):
    def clean_password1(self):
        passwd = self.cleaned_data['password1']
        if passwd and len(passwd) < 6:
            raise ValidationError('password too short.')
        return passwd

class myUserAdmin(UserAdmin):
    add_form = myUserCreationForm
    change_password_form = myAdminPasswordChangeForm

# registration
admin.site.unregister(User)
admin.site.register(User, myUserAdmin)

Add this to an admin.py file. This should be enough to get you started.

To answer the question below (comments not working right now?):
1) I was told the name by the guy on IRC. It could probably be found by checking the source as well, if you knew where to look.
2) Override by subclassing the object. Import it and create a class as done above.

2 comments:

  1. Thanks for posting this. I have a couple of questions. 1) How did you pick the variable change_password_form under myUserAdmin for the value of myAdminPasswordChangeForm. 2) How would I override the default PasswordChangeForm?

    ReplyDelete
  2. Holy crap that change_password_form solved my last unknown issue, thx! :)

    ReplyDelete