Skip to content
Advertisement

I want Staffuser in Django not to see any superusers

Right now i have applied this code

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):
    def get_fieldsets(self,request,obj=None):
        if not obj:
            return self.add_fieldsets
        
        if request.user.is_superuser:
            perm_fields = ('is_active','is_staff','is_superuser','groups','user_permissions')

            return [(None, {'fields': ('email', 'password')}),
                    ('Personal info', {'fields': ('first_name', 'last_name')}),
                    ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
                    ('Important dates', {'fields': ('last_login', 'date_joined')}),
                    ('Contact info', {'fields': ('contact_no',)})]
        else:
            perm_fields = ('is_active','is_staff')
        
            return [(('Creds'),{'fields':('username','password')}),
                    (('Personal info'),{'fields':('first_name','last_name','email')})]

admin.site.unregister(User)
admin.site.register(User,MyUserAdmin)

Here all the staff user are able to see superuser when i am logged in as staffuser enter image description here

But I want that the staffuser wont be able to see any superuser. so in this case staffuser can only view 1 user which is “new” and “admin” user which is superuser, should be hidden

How can i do that ?

Advertisement

Answer

You need to override get_queryset method:

 def get_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        
        return qs.filter(is_superuser=False)
Advertisement