A short note on how to fix the queryset administration form admin.ModelAdmin or UserAdmin . Actually, there is no difference, since the form UserAdmin is inherited from admin.ModelAdmin . Nevertheless, I will show UserAdmin as an example.
The task is as follows. The site has superusers and users from the administration. Superusers can see all users and edit as they like. And administration users can see all user records except superusers, and also can not appoint other users as superusers.
And now to the solution. This form will look as follows.
# -*- coding: utf-8 -*- from django.contrib.auth.admin import UserAdmin class EUserAdmin(UserAdmin): def get_readonly_fields(self, request, obj=None): # We make the field uneditable if the user is not a superuser return super().get_readonly_fields(request) if request.user.is_superuser else ('is_superuser',) def get_queryset(self, request): qs = super().get_queryset(request) # and also exclude all superusers from queryset if the user is not a superuser return qs if request.user.is_superuser else qs.exclude(is_superuser=True)
Such restrictions are useful if you want to protect the superuser from editing by ordinary users from the administration.