Do not allow admin users to modify a username after it has been created
authorJonathan S. Katz <jonathan.katz@excoventures.com>
Thu, 26 Jun 2014 13:36:21 +0000 (09:36 -0400)
committerJonathan S. Katz <jonathan.katz@excoventures.com>
Thu, 26 Jun 2014 14:47:17 +0000 (10:47 -0400)
This involves some changes to how the default Django UserAdmin is handled with
respect to saving the form, but we simply override the changes to keep all
of the default Django functionality intact, minus allowing a username to be
modified on edit.

pgweb/account/admin.py

index 09b51b4c0cec4897ebd26e39fed91350dcdb0dc4..beb1a016eac83d6b2cc69aa8493b1497462362a4 100644 (file)
@@ -1,4 +1,7 @@
 from django.contrib import admin
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.auth.forms import UserChangeForm
+from django.contrib.auth.models import User
 from django import forms
 
 import base64
@@ -23,5 +26,27 @@ class CommunityAuthSiteAdminForm(forms.ModelForm):
 class CommunityAuthSiteAdmin(admin.ModelAdmin):
        form = CommunityAuthSiteAdminForm
 
-               
+class PGUserChangeForm(UserChangeForm):
+       """just like UserChangeForm, butremoves "username" requirement"""
+       def __init__(self, *args, **kwargs):
+               super(PGUserChangeForm, self).__init__(*args, **kwargs)
+               # because the auth.User model is set to "blank=False" and the Django
+               # auth.UserChangeForm is setup as a ModelForm, it will always validate
+               # the "username" even though it is not present.  Thus the best way to
+               # avoid the validation is to remove the "username" field, if it exists
+               if self.fields.get('username'):
+                       del self.fields['username']
+
+class PGUserAdmin(UserAdmin):
+       """overrides default Django user admin"""
+       form = PGUserChangeForm
+
+       def get_readonly_fields(self, request, obj=None):
+               """this prevents users from changing a username once created"""
+               if obj:
+                       return self.readonly_fields + ('username',)
+               return self.readonly_fields
+
 admin.site.register(CommunityAuthSite, CommunityAuthSiteAdmin)
+admin.site.unregister(User) # have to unregister default User Admin...
+admin.site.register(User, PGUserAdmin) # ...in order to add overrides
\ No newline at end of file