Skip to content

Instantly share code, notes, and snippets.

@dstegelman
Last active October 7, 2015 11:08
Show Gist options
  • Save dstegelman/3156048 to your computer and use it in GitHub Desktop.
Save dstegelman/3156048 to your computer and use it in GitHub Desktop.
Check for group affiliation in Django tempalte
from django import template
from django.template import resolve_variable
from django.contrib.auth.models import Group
register = template.Library()
@register.tag()
def ifusergroup(parser, token):
""" Check to see if the currently logged in user belongs to a specific
group. Requires the Django authentication contrib app and middleware.
Usage: {% ifusergroup Admins %} ... {% endifusergroup %}
"""
try:
tag, group = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("Tag 'ifusergroup' requires 1 argument.")
nodelist = parser.parse(('endifusergroup',))
parser.delete_first_token()
return GroupCheckNode(group, nodelist)
class GroupCheckNode(template.Node):
def __init__(self, group, nodelist):
self.group = group
self.nodelist = nodelist
def render(self, context):
user = resolve_variable('user', context)
if not user.is_authenticated:
return ''
try:
group = Group.objects.get(name=self.group)
except Group.DoesNotExist:
return ''
if group in user.groups.all():
return self.nodelist.render(context)
return ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment