Last active
December 8, 2023 15:17
-
-
Save DArmstrong87/02544bf146846f142d7e92c4a22b803d to your computer and use it in GitHub Desktop.
Custom django template filter to check if user is in allowed groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.contrib.auth import get_user_model | |
from django.contrib.auth.models import Group | |
register = template.Library() | |
User = get_user_model() | |
@register.filter(name="user_in_group") | |
def user_is_in_group(user: User, allowed_groups: str) -> bool: | |
""" | |
'allowed_groups' should be a comma-separated string with no spaces. | |
Return if user is in one of the allowed groups | |
""" | |
allowed_groups = allowed_groups.split(",") | |
groups = Group.objects.filter(name__in=allowed_groups) | |
return user.groups.filter(id__in=groups.values_list("id", flat=True)).exists() | |
# Usage in template: | |
# {% if user|user_in_group:"Group 1,Group 2" %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment