Login

Link TemplateTag that checks for permissions and url address

Author:
mlouro
Posted:
May 20, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This template tag was built to be used in web applications that are permission based. It renders the html for an html link tag if the user has permissions to access the view (if not, returns an empty string). It also checks if the current token is the active url address and, if so, adds class="active" to the html link for presentation purposes.

Example usage:

  1. {% url home as home_url %} {% get_link_if_allowed home_url "Home" %}

  2. {% url project_dashboard project.id as project_dashboard_url %} {% get_link_if_allowed project_dashboard_url "Projects" %}

 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
# -*- coding: utf-8 -*-
from django.template import Node, Library, TemplateSyntaxError, VariableDoesNotExist
from django.core.urlresolvers import reverse, resolve
from django.template.defaulttags import URLNode
from django.contrib.auth.decorators import user_passes_test

register = Library()

class LinkAllowedNode(Node):
    def __init__(self, url, name, permission):
        self.url = url
        self.permission = permission
        self.name = name


    def render(self, context):
        request = context['request']
        url = self.url.resolve(context)

        if self.permission and not request.user.has_perm(self.permission.resolve(context)):
            return ''

        import re
        pattern = "^%s$" % url

        if re.search(pattern, request.path):
            return '<li><a href="%s" title="%s" class="active">%s</a></li>' % (url,self.name.resolve(context),self.name.resolve(context))
        return '<li><a href="%s" title="%s">%s</a></li>' % (url,self.name.resolve(context),self.name.resolve(context))


def get_link_if_allowed(parser, token):

    bits = token.contents.split()
    if len(bits) == 3:
        permission = ''
    elif len(bits) < 3 or len(bits) > 5:
        raise TemplateSyntaxError, "get_link_if_permssions tag takes two or three arguments {% get_link_if_allowed url title permission %}"
    else:
        permission = parser.compile_filter(bits[3])

    return LinkAllowedNode(parser.compile_filter(bits[1]),parser.compile_filter(bits[2]),permission)

get_link_if_allowed = register.tag(get_link_if_allowed)

More like this

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

Comments

Please login first before commenting.