- Author:
- mlouro
- Posted:
- May 20, 2009
- Language:
- Python
- Version:
- 1.0
- Tags:
- template url permissions address
- 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:
-
{% url home as home_url %} {% get_link_if_allowed home_url "Home" %}
-
{% 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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 4 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago
Comments
Please login first before commenting.