I have two diffeent fieldsets depending on wether a user is in the 'leader' group or not. The fieldset show exactly what I want, except when I try to add a new user, from a user in the 'Leader' group, I now get a different user creation form. I got how to do the different fieldsets from here, and I tried ensuring the form is indeed the right one by overriding the custom form as done here.
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2')
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'UserProfile'
fk_name = 'scout_username'
class CustomUserAdmin(UserAdmin):
#ensuring it's the right form
add_form = UserCreateForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2'),
}),
)
inlines = (UserProfileInline, )
fieldsets = (
((None), {'fields': ('username', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
leader_fieldsets = (
((None), {'fields': ('username', 'password')}),
(('Personal'), {'fields': ('first_name', 'last_name')}),
)
#making it so leaders can only view the fields within leaders_fieldset
#removing this also removes the problem yet all the fields are shown regardless of the user's group
def get_fieldsets(self, request, obj=None):
if request.user.groups.filter(name='Leader').exists():
return self.leader_fieldsets
else:
return super(CustomUserAdmin, self).get_fieldsets(request, obj=obj)
#adding the userprofile stuff to the user change form
def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
If the user is not in the 'Leader' group I get the original user creation form. User Creation Form if user is not in Leader Group
Else I get a form with the fields, username
, password
(which is not a password type as anything written in it is clear text) and then I get first name
and last name
.
User Creation Form if user is in Leader Group
Could someone please explain to me why this is happening and what I can do to fix it?
A little trick which worked for this particular case follows the fact that the url always had 'ADD' at the end. Thus by checking if it was the user-add form currently on the page a function could return true or false.
def is_add_form(request):
path_info = request.META.get('PATH_INFO')
last_path = str(path_info.split('/')[-2])
if last_path == 'add':
return True
else:
return False
This worked with great success and I hope it helps others.