Skip to content

Instantly share code, notes, and snippets.

@thanos
Created December 16, 2015 14:47
Show Gist options
  • Save thanos/f020925f143e1a66cacf to your computer and use it in GitHub Desktop.
Save thanos/f020925f143e1a66cacf to your computer and use it in GitHub Desktop.
A custom django has_group conditional tag for testing if a user belongs to a group in a django template.
# A custom django has_group conditional tag
# usage:
#
# {% if request.user|has_group:"Manager" %} {% endif %}
#
# Developer: Thanos Vassilakis, 2002
import re, string
from django import template
register = template.Library()
from django.contrib.auth.models import Group
@register.filter(name='has_group')
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 Group.DoesNotExist:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment