In Django, how do I check if a user is in a certain group?

前端 未结 12 2017
借酒劲吻你
借酒劲吻你 2020-11-28 18:25

I created a custom group in Django\'s admin site.

In my code, I want to check if a user is in this group. How do I do that?

12条回答
  •  Happy的楠姐
    2020-11-28 18:38

    If you need the list of users that are in a group, you can do this instead:

    from django.contrib.auth.models import Group
    users_in_group = Group.objects.get(name="group name").user_set.all()
    

    and then check

     if user in users_in_group:
         # do something
    

    to check if the user is in the group.

提交回复
热议问题