How to not let staff or admin users edit superusers

I'm working on permission distribution and according to my user model structure, staff and admin users are allowed to edit is_staff and is_admin for other users, not themselves. But with such power, they are able to edit those booleans for superusers too, which I don't them to have permission for! so, how do I let staff and admin users edit those booleans for others except superusers and themselves? or to not let staff and admin users get permission to tamper with any superuser attributes

admin

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    is_superuser = request.user.is_superuser
    is_admin = request.user.is_admin
    disabled_fields = set()

    if (
        not is_superuser
        and obj is not None
        and obj == request.user
    ):
        disabled_fields |= {
            'staff',
            'admin',
            'user_permissions',
        }

    for f in disabled_fields:
        if f in form.base_fields:
            form.base_fields[f].disabled = True

    return form

I have another suggest to you, you can use Django Group permission

create a specific group permission and add any user you want to it

You can manage is_superuser boolean field using form for preventing non-superusers can not change is_superuser flag of any superuser and manage self user changes by using permission method. Also you can use modeladmin get_readonly_fields() method for partial field disable.

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    is_superuser = request.user.is_superuser
    disabled_fields = set()
    # Prevent non-superusers from changing user's superuser boolean field
    if not is_superuser:
        disabled_fields |= {
            'is_superuser',
        }
    for f in disabled_fields:
        if f in form.base_fields:
            form.base_fields[f].disabled = True
    return form

def has_add_permission(self, request):
    opts = self.opts
    codename = get_permission_codename('add', opts)
    user_has_add = request.user.has_perm("%s.%s" % (opts.app_label, codename))
    if user_has_add and self.is_user_not_allowed(request.user, None):
        return False
    return user_has_add

def has_change_permission(self, request, obj=None):
    opts = self.opts
    codename = get_permission_codename('change', opts)
    user_has_change = request.user.has_perm("%s.%s" % (opts.app_label, codename))
    if user_has_change and obj is not None and self.is_user_not_allowed(request.user, obj):
        return False
    return user_has_change


def is_user_not_allowed(self, user, obj=None):
    if not user.is_superuser and obj is not None and obj == user:
        # Prevent non-superusers from editing their own permissions
        return True
    return False
Back to Top