Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Created August 21, 2014 04:33
Show Gist options
  • Select an option

  • Save arthuralvim/78129975b31d457fffc6 to your computer and use it in GitHub Desktop.

Select an option

Save arthuralvim/78129975b31d457fffc6 to your computer and use it in GitHub Desktop.
A template tag to check if an user belongs to a specific group.
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else False
{% if request.user|has_group:"mygroup" %}
<p>User belongs to my group
{% else %}
<p>User doesn't belong to mygroup</p>
{% endif %}
- See more at: http://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/#sthash.xY5PrSGC.dpuf
@hek444
Copy link
Copy Markdown

hek444 commented Feb 26, 2023

I've added try except, because if the group doesn't exist I've got error

def has_group(user, group_name):
    try:
        group = Group.objects.get(name=group_name)
        return True if group in user.groups.all() else False
    except:
        return False

@dimitrismistriotis
Copy link
Copy Markdown

dimitrismistriotis commented May 26, 2024

I suggest using Django's ORM filter(...).first() if you want to avoid try/catch as it returns None if nothing found.

Using the walrus operator I wrote it this way:

@register.filter(name="has_group")
def has_group(user, group_name) -> bool:
    """Check if User Belongs to Given Group.

    This should be avoided as it is better to have specific permissions attached
    to models.

    Use:
    ...

    {% if request.user|has_group:"mygroup" %}
      <p>User belongs to my group
    {% else %}
      <p>User doesn't belong to mygroup</p>
    {% endif %}
    """
    if group := Group.objects.filter(name=group_name).first():
        return group in user.groups.all()

    return False

Plus there is no reason to return True if ..., in operator https://docs.python.org/3/reference/expressions.html#in returns boolean, there is no need to check if boolean, you can return just that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment