简体   繁体   中英

how to check if a user is in a default django group? in the admin panel (admin.py)

My logic is that when a user with is_stuff privilege went to the admin panel and tried to create, for example, news, then the program checked him, in which group he is, if this group exists, then it should issue fieldsets with limited capabilities, or other fields...

I checked this link ( In Django, how do I check if a user is in a certain group? ), but it does not work for my situation, since I have to check in the admin panel not return it to api or templates.

i tried to do the following: in admin.py (a)

    def get_fieldsets(self, request, obj=None):
       group = Group(name="OutSource")
       if request.user.groups(name=group):
          # first_fields = {...}
       else:
          # second_fields = {...}

callback:

TypeError: 'NoneType' object is not callable

admin.py (b):

if request.user.groups.all()[0].name == "OutSource":

callback:

IndexError: list index out of range

admin.py (c):

if request.user.groups.filter(name='OutSource').exists():

callback:

unhashable type: 'dict'

I'm sorry, I found a solution to my question. Here is the answer if anyone needs it

def get_fieldsets(self, request, obj=None):
    users_in_group = Group.objects.get(name="OutSource").user_set.all()
    if request.user in users_in_group:
       # fields = (...)
    else:
       # fields = (...)
    return fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM