Skip to content

Instantly share code, notes, and snippets.

@danielsokolowski
Created July 30, 2012 17:34
Show Gist options
  • Save danielsokolowski/3208570 to your computer and use it in GitHub Desktop.
Save danielsokolowski/3208570 to your computer and use it in GitHub Desktop.
Returns an html string node useful for providing a visual cue to the permission group required; django-guradian required.
from django import template, template
from django.contrib.auth.models import Group
from guardian.shortcuts import get_groups_with_perms
register = template.Library()
class ObjectGroups(template.Node):
"""
Returns an html string node useful for providing a visual cue to the
permission group required.
Example of usage (assuming ``flatpage`` is available from *context*)::
<h1>{% obj_groups flatpage %}{{flatpage.title}}</h1>
would result in:
<h1><span class='clsPaid clsRegister [cls...]'>&nbsp;</span>{{flatpage.title}}</h1>
"""
def __init__(self, obj):
self.obj = obj # resolved in render method as needed
def render(self, context):
### check against an instance or a model class
instance = template.Variable(self.obj).resolve(context)
instance_groups = get_groups_with_perms(instance)
html = '<span title="Access Level: %s" class="%s">&nbsp;</span>'
titles = ''
classes = ''
for group in instance_groups:
titles = titles + '%s ' % group.name
classes = classes + 'cls%s ' % group.name
html = html % (titles, classes)
return html
@register.tag # this is just synonym with register.tag('get_obj_groups', get_obj_groups)
def obj_groups(parser, args):
tag_template_syntax = "Tag's syntax is {%% %s <obj_instance> %%}"
try:
# split_contents() knows not to split quoted strings.
tag_name, obj = args.split_contents()
except ValueError:
raise template.TemplateSyntaxError(tag_template_syntax % args.contents.split()[0])
return ObjectGroups(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment