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

Your User object is linked to the Group object through a ManyToMany relationship.

You can thereby apply the filter method to user.groups.

So, to check if a given User is in a certain group (“Member” for the example), just do this :

def is_member(user):
    return user.groups.filter(name="Member").exists()

If you want to check if a given user belongs to more than one given groups, use the __in operator like so :

def is_in_multiple_groups(user):
    return user.groups.filter(name__in=['group1', 'group2']).exists()

Note that those functions can be used with the @user_passes_test decorator to manage access to your views :

from django.contrib.auth.decorators import login_required, user_passes_test

@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
    # Do your processing

For class based views, you might use UserPassesTestMixin with test_func method:

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class MyView(LoginRequiredMixin, UserPassesTestMixin, View):

    login_url="/login/"
    redirect_field_name="redirect_to"

    def test_func(self):
        return is_member(self.request.user)

Hope this help

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)