Marek Szmalc Marek Szmalc - 2 months ago 18
Python Question

Exclude fields in Django admin for users other than superuser

I have a simple

MyUser
class with
PermissionsMixin
.
user.is_superuser
equals
True
only for superusers. I'd like to be able to do something similar to this in my
admin.py
:

if request.user.is_superuser:
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_admin','is_staff')}),
('Place', {'fields': ('place',)}),
('Important dates', {'fields': ('last_login',)}),
)
else:
fieldsets = (
(None, {'fields': ('email', 'password')}),
#('Permissions', {'fields': ('is_admin','is_staff')}),
('Place', {'fields': ('place',)}),
('Important dates', {'fields': ('last_login',)}),
)


Basically I want my users to be able to create other users, but not give them admin or stuff permissions. Only superusers should be able to do that.

Answer

If I understand you correctly, what you want to do is override the get_form method for the ModelAdmin. Base on the example from django documentation, it would look something like this:

class MyUserAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        self.exclude = []
        if not request.user.is_superuser:
            self.exclude.append('Permissions') #here!
        return super(MyUserAdmin, self).get_form(request, obj, **kwargs)

Now you might need to hack around a little and maybe override the save method as well. I did something similar not long ago, it's not so complicated (and the docs are fantastic).

There might be a simpler solution but your question is kinda general and you didn't share your user model, so I can't tell you exactly how to work this out. I hope this helps!