Login

User group template tag

Author:
jdriscoll
Posted:
June 13, 2007
Language:
Python
Version:
.96
Tags:
tag templatetag user auth group
Score:
7 (after 7 ratings)

An "if-style" template tag that checks to see if a user belongs to a specific group (by name).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 ''

More like this

  1. User groups template tag by hijinks 5 years, 9 months ago
  2. User group template tag with "else" block support by GomoX 7 years, 7 months ago
  3. User groups template tag with "else" block support (Allow checking several groups) by br0th3r 2 years, 11 months ago
  4. User groups template tag by davea 3 years, 5 months ago
  5. Template tag: Group variables into list by Killarny 6 years ago

Comments

GomoX (on August 26, 2007):

Line 30 should read: if not user.is_authenticated()

Is authenticated is a method, not an attribute. Oddly it seems to work fine despite that.

#

Please login first before commenting.