Django admin - how to hide some fields in User edit?

robos85 picture robos85 · Jul 4, 2011 · Viewed 7.9k times · Source

How can I hide fields in admin User edit? Mainly I want to hide permissions and groups selecting in some exceptions, but exclude variable doesn't work :/

Answer

Pannu picture Pannu · Mar 21, 2012

I may be late to answer this question but any ways, here goes. John is right in concept but I just wanted to do this because I know django admin is truly flexible.

Any way's the way you hide fields in User model form is:

1. exclude attribute of the ModelAdmin class can be used to hide the fields.

2: The should allow blank in model.

3: default attribute on model field is an advantage or you might get unexpected errors.

The problems I had was that I used to get a validation error. I looked at the trace back and found out that the error was because of UserAdmin's fieldsets grouping, the default permission field set has user_permission override this in your sub-calassed model admin.

Use the exclude attribute in get_form where you can access request variable and you can set it dynamical depending on the user's permission or group.

Code:

admin.py:

class MyUserAdmin(UserAdmin): 

     list_display = ("username","first_name", "last_name", "email","is_active","is_staff","last_login","date_joined")

     ## Static overriding 
     fieldsets = (
         (None, {'fields': ('username', 'password')}),
         (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
         (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                    'groups')}),
     (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
     )


     def get_form(self, request, obj=None, **kwargs):
         self.exclude = ("user_permissions")
         ## Dynamically overriding
         self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff','is_superuser','groups')
         form = super(MyUserAdmin,self).get_form(request, obj, **kwargs)
         return form