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

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?

This question is related to python django django-authentication

The answer is


In one line:

'Groupname' in user.groups.values_list('name', flat=True)

This evaluates to either True or False.


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

Hope this help


I did it like this. For group named Editor.

# views.py
def index(request):
    current_user_groups = request.user.groups.values_list("name", flat=True)
    context = {
        "is_editor": "Editor" in current_user_groups,
    }
    return render(request, "index.html", context)

template

# index.html
{% if is_editor %}
  <h1>Editor tools</h1>
{% endif %}

You just need one line:

from django.contrib.auth.decorators import user_passes_test  

@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
    return HttpResponse("Since you're logged in, you can see this text!")

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.


Just in case if you wanna check user's group belongs to a predefined group list:

def is_allowed(user):
    allowed_group = set(['admin', 'lead', 'manager'])
    usr = User.objects.get(username=user)
    groups = [ x.name for x in usr.groups.all()]
    if allowed_group.intersection(set(groups)):
       return True
    return False

If a user belongs to a certain group or not, can be checked in django templates using:

{% if group in request.user.groups.all %} "some action" {% endif %}


If you don't need the user instance on site (as I did), you can do it with

User.objects.filter(pk=userId, groups__name='Editor').exists()

This will produce only one request to the database and return a boolean.


I have done it the following way. Seems inefficient but I had no other way in my mind:

@login_required
def list_track(request):

usergroup = request.user.groups.values_list('name', flat=True).first()
if usergroup in 'appAdmin':
    tracks = QuestionTrack.objects.order_by('pk')
    return render(request, 'cmit/appadmin/list_track.html', {'tracks': tracks})

else:
    return HttpResponseRedirect('/cmit/loggedin')

User.objects.filter(username='tom', groups__name='admin').exists()

That query will inform you user : "tom" whether belong to group "admin " or not


I have similar situation, I wanted to test if the user is in a certain group. So, I've created new file utils.py where I put all my small utilities that help me through entire application. There, I've have this definition:

utils.py

def is_company_admin(user):
    return user.groups.filter(name='company_admin').exists()

so basically I am testing if the user is in the group company_admin and for clarity I've called this function is_company_admin.

When I want to check if the user is in the company_admin I just do this:

views.py

from .utils import *

if is_company_admin(request.user):
        data = Company.objects.all().filter(id=request.user.company.id)

Now, if you wish to test same in your template, you can add is_user_admin in your context, something like this:

views.py

return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})

Now you can evaluate you response in a template:

users.html

{% if is_company_admin %}
     ... do something ...
{% endif %}

Simple and clean solution, based on answers that can be found earlier in this thread, but done differently. Hope it will help someone.

Tested in Django 3.0.4.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-authentication

How to get the currently logged in user's user id in Django? In Django, how do I check if a user is in a certain group? Having Django serve downloadable files Extending the User model with custom fields in Django