Login

Templatetag for granular permissions

Author:
achimnol
Posted:
June 24, 2009
Language:
Python
Version:
1.0
Tags:
template templatetag
Score:
0 (after 0 ratings)

If you're using Django granular permissions, this templatetag may be useful.

It enables you to check permission in templates, as mentioned in the code:

{% has_row_perm user object "staff" as some_var %}
{% if some_var %}
...
{% endif %}

To be used in if statements, it always saves the result to the indicated context variable.

Put the snippet in row_perms.py in yourapp.templatetags package, and use {% load row_perms %} at your template.

 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
# -*- encoding: utf8 -*-
from django import template
from django.contrib.auth.models import User

register = template.Library()

class HasRowPermNode(template.Node):
    def __init__(self, user, labsite, perm, varname):
        self.user = template.Variable(user)
        self.labsite = template.Variable(labsite)
        self.perm = perm
        self.varname = varname

    def __repr__(self):
        return '<HasRowPerm node>'

    def render(self, context):
        user = self.user.resolve(context)
        labsite = self.labsite.resolve(context)
        context[self.varname] = user.has_row_perm(labsite, self.perm)
        return ''

def _check_quoted(string):
    return string[0] == '"' and string[-1] == '"'

@register.tag('has_row_perm')
def do_has_row_perm(parser, token):
    """
    A has-row-perm boolean indicator tag for django templates.

    Example usage:
        {% has_row_perm user object "staff" as some_var %}
        {% if some_var %}
        ...
        {% endif %}
    """

    try:
        tokens = token.split_contents()
        tag_name = tokens[0]
        args = tokens[1:]
    except ValueError, IndexError:
        raise template.TemplateSyntaxError('%r tag requires arguments.' % tag_name)

    if _check_quoted(args[0]) or _check_quoted(args[1]) or not _check_quoted(args[2]) \
        or args[3] != 'as' or _check_quoted(args[4]):
        raise template.TemplateSyntaxError('%r tag had invalid argument.' % tag_name)

    return HasRowPermNode(args[0], args[1], args[2][1:-1], args[4])

More like this

  1. Functional Filters by waterson 7 years, 7 months ago
  2. A templatetag to insert the output of another view (or local URL) by jamesgpearce 5 years, 11 months ago
  3. favicon Template Tag by benjy_mouse 5 years, 3 months ago
  4. shuffle templatetag by deanmalmgren 4 years, 2 months ago
  5. Row-Level, URL-based permissions for FlatPages by bradmontgomery 5 years, 11 months ago

Comments

Please login first before commenting.