how to not let staff or admin users edit superusers

Question:

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
Asked By: betty_

||

Answers:

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

Answered By: Hashem

You can remove edit permission for any superuser from non-superusers.

from django.contrib.auth import get_permission_codename

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.is_superuser:
        # Prevent non-superusers from editing any superuser
        return True
    return False
Answered By: Md Shahbaz Ahmad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.