Login

User groups template tag

Author:
davea
Posted:
October 9, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

This snippet is an improved version of the ifusergroup tag that allows spaces in any of the group names. It also fixes a small bug where if a group didn't exist none of the subsequent groups would be checked.

 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
from django import template
from django.template import resolve_variable, NodeList
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 %}, or
           {% ifusergroup Admins|Group1|"Group 2" %} ... {% endifusergroup %}, or
           {% ifusergroup Admins %} ... {% else %} ... {% endifusergroup %}
    
    """
    try:
        tag, group = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("Tag 'ifusergroup' requires 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(group, nodelist_true, nodelist_false)


class GroupCheckNode(template.Node):
    def __init__(self, group, nodelist_true, nodelist_false):
        self.group = group
        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)
        
        for group in self.group.split("|"):
            group = group[1:-1] if group.startswith('"') and group.endswith('"') else group
            try:
                if Group.objects.get(name=group) in user.groups.all():
                    return self.nodelist_true.render(context)
            except Group.DoesNotExist:
                pass
        
        return self.nodelist_false.render(context)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

kl4us (on September 25, 2013):

Well done, useful snippet. I added an IF statement:

if user.is_superuser:
    return self.nodelist_true.render(context)

#

Please login first before commenting.