adlius45
adlius45

Reputation: 39

How to exclude instances from Admin site in Django

In Django, I have created another separate Admin site. This is what my SiteUserAdmin class looks like:

class SiteUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm

list_display = ('username' ,'email',)

fieldsets = (
    (None,{'fields':('username','email','password')}),('Permissions',{'fields':('is_active','is_admin_user','groups')})
)

Among all the users, there are superusers whose "is_superuser = True". Is there anyway to hide such superusers from the list of editable users of the admin site? In another word, I am not excluding other fields from the Admin site, but rather hide some instances of User from being edited in the Admin site.

Upvotes: 1

Views: 228

Answers (2)

mishbah
mishbah

Reputation: 5607

How about just overriding the get_queryset() method.

class SiteUserAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(SiteUserAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(is_superuser=False)

Docs: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset

Upvotes: 4

catavaran
catavaran

Reputation: 45575

Override the get_queryset() method:

class SiteUserAdmin(UserAdmin):
    ...
    def get_queryset(self, request):
        qs = super(SiteUserAdmin, self).get_queryset(request)
        return qs.exclude(is_superuser=True)

Upvotes: 2

Related Questions