Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin is_staff based on group

Is it possible to have is_staff selected by choosing a group? Let's say there are two groups: users, admins

When a new user is in the users group he is not staff, but if he is in the admins group he is staff.

like image 239
DaViDa Avatar asked Mar 29 '16 12:03

DaViDa


3 Answers

There is an easy way to do this define the following in your user model

@property
def is_staff(self):
    if self.is_staff == True or self.groups.filter(name="staff").exists()

Thus during admin login or any other time when you call from the user_object.is_staff You will be getting what you want on basis of groups too.

like image 78
mascot6699 Avatar answered Nov 12 '22 18:11

mascot6699


I managed to make it work by extending the UserAdmin class and in the get_form function I placed this with help of mascot6699's answer:

if obj.groups.filter(name="Administrator").exists():
    obj.is_staff = True
else:
    obj.is_staff = False

So whenever I place a user (with the admin menu) in the Administrator group it will check the is_staff option else it unchecks it.

like image 38
DaViDa Avatar answered Nov 12 '22 18:11

DaViDa


The is_staff property is primarily used by the admin interface. If you want to have an admin interface that's dependent on group membership, you can override AdminSite.has_permission() instead:

class GroupBasedAdminSite(admin.AdminSite):
    def has_permission(self, request):
        return request.user.is_active and request.user.groups.filter(name = 'admins').exists()

# override default admin site
admin.site = GroupBasedAdminSite()

You can also use the official override feature, or have a dedicated GroupBasedAdminSite hosted on a different path, in case you want to support different types of "admins".

like image 2
ge0rg Avatar answered Nov 12 '22 17:11

ge0rg