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

Question

Asked By – TIMEX

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?

Now we will see solution for issue: In Django, how do I check if a user is in a certain group?


Answer

You can access the groups simply through the groups attribute on User.

from django.contrib.auth.models import User, Group

group = Group(name = "Editor")
group.save()                    # save this new group for this example
user = User.objects.get(pk = 1) # assuming, there is one initial user 
user.groups.add(group)          # user is now in the "Editor" group

then user.groups.all() returns [<Group: Editor>].

Alternatively, and more directly, you can check if a a user is in a group by:

if django_user.groups.filter(name = groupname).exists():

    ...

Note that groupname can also be the actual Django Group object.

This question is answered By – miku

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0