An example of how to modify the admin user creation form to assign an unusable password to externally authenticated users when they are created.
This code is more intimate with the django.contrib.auth classes than I'd like, but it should be fairly straightforward to maintain should the relevant django.contrib.auth classes change.
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 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.
<div class="form-row">
<label for="id_is_ldap_authenticated" class="required">
LDAP authenticated:</label> {{ form.is_ldap_authenticated }}
</div>
"""
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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.