Login

User groups template tag with "else" block support (Allow checking several groups)

Author:
br0th3r
Posted:
April 29, 2012
Language:
Python
Version:
1.4
Tags:
tag templatetag user auth group
Score:
2 (after 2 ratings)

An "if-style" template tag that checks to see if a user belongs to a one or mores groups (by name).

Usage: {% ifusergroup Admins %} ... {% endifusergroup %} or {% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %}

 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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 one or more groups
    Requires the Django authentication contrib app and middleware.

    Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or
           {% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %}

    """
    try:
        tokensp = token.split_contents()
        groups = []
        groups+=tokensp[1:]
    except ValueError:
        raise template.TemplateSyntaxError("Tag 'ifusergroup' requires at least 1 argument.")
    
    nodelist_true = parser.parse(('else', 'endifusergroup'))
    token = parser.next_token()
    
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifusergroup',))
        parser.delete_first_token()
    else:
        nodelist_false = NodeList()
    
    return GroupCheckNode(groups, nodelist_true, nodelist_false)


class GroupCheckNode(template.Node):
    def __init__(self, groups, nodelist_true, nodelist_false):
        self.groups = groups
        self.nodelist_true = nodelist_true
        self.nodelist_false = nodelist_false
    def render(self, context):
        user = resolve_variable('user', context)
        
        if not user.is_authenticated():
            return self.nodelist_false.render(context)
        
        allowed=False
        for checkgroup in self.groups:
            try:
                group = Group.objects.get(name=checkgroup)
            except Group.DoesNotExist:
                break
                
            if group in user.groups.all():
                allowed=True
                break
        
        if allowed:
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

More like this

  1. User group template tag with "else" block support by GomoX 8 years ago
  2. User group template tag by jdriscoll 8 years, 2 months ago
  3. User groups template tag by hijinks 6 years, 2 months ago
  4. User groups template tag by davea 3 years, 10 months ago
  5. mark a required field by "*" in a template by brunobord 7 years, 9 months ago

Comments

kourosh (on June 18, 2012):

it gives me the following error Django Version: 1.4 Exception Type: NameError Exception Value: global name 'NodeList' is not defined

#

kourosh (on June 18, 2012):

add this to work -> from django.template import resolve_variable, NodeList

#

Please login first before commenting.