from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class ExternalUserCreationForm(UserCreationForm):
"""
In your templates directory create a version of admin/auth/user/add_user.html
that includes the is_ldap_authenticated field. E.g.
{{ form.is_ldap_authenticated }}
"""
is_ldap_authenticated = forms.BooleanField(initial=True, required=False)
def _is_ldap_user(self):
result = False
if self.cleaned_data.has_key('is_ldap_authenticated'):
result = self.cleaned_data['is_ldap_authenticated']
return result
def clean(self):
cleaned_data = super(ExternalUserCreationForm, self).clean()
# Ignore password errors if we aren't using the password field
if self._is_ldap_user():
if self.errors.has_key('password1'):
del self.errors['password1']
if self.errors.has_key('password2'):
del self.errors['password2']
return cleaned_data
def save(self, commit=True):
if self._is_ldap_user():
user = super(UserCreationForm, self).save(commit=False)
user.set_unusable_password()
if commit:
user.save()
else:
user = super(ExternalUserCreationForm, self).save(commit=commit)
return user
class ExtendedUserAdmin(UserAdmin):
add_form = ExternalUserCreationForm
admin.site.unregister(User)
admin.site.register(User, ExtendedUserAdmin)