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?
In one line:
'Groupname' in user.groups.values_list('name', flat=True)
This evaluates to either True
or False
.
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.
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!")
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
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 %}
User.objects.filter(username='tom', groups__name='admin').exists()
That query will inform you user : "tom" whether belong to group "admin " or not