Derek Stegelman

Snippet Sunday: Check Group Affiliation in Templates

Sunday snippets are bits of code that I’ve found useful in past projects. I post them here in hopes that someone else will find them useful. Most of these are Github Gists and you can follow them there too if you want.

I often need to show or hide some piece of functionality for certain groups in web applications. It’s hard to check this without some sort of context processor that sends group information to the template on each request. This weeks Sunday Snippet is a template tag you can drop in that will do this for you. As with all Sunday Snippets, check out my Github gist page for this and more.

from django import template
from django.template import resolve_variable
from django.contrib.auth.models import Group

register = template.Library()

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.

tag, group = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("Tag 'ifusergroup' requires 1 argument.")
nodelist = parser.parse(('endifusergroup',))
return GroupCheckNode(group, nodelist)

class GroupCheckNode(template.Node):
def __init__(self, group, nodelist): = group
self.nodelist = nodelist
def render(self, context):
user = resolve_variable('user', context)
if not user.is_authenticated:
return ''
group = Group.objects.get(
except Group.DoesNotExist:
return ''
if group in user.groups.all():
return self.nodelist.render(context)
return ''