I'm trying to run a custom template tag, but I have some difficulties when I apply the tag in a for loop with multiple elements in a repeating thing.
I would like the tag to look below and only display the text “WORKED” if my permission function is True.
Pattern code
{% load permission_tags %}
{% for group in groups %}
<div>{% permission request.user can_edit_group on group %}WORKED{% endpermission %}</div>
{% endfor %}
The main tag uses a user instance, a permission string (that is, "can_edit_group"), the keyword "on" (only to make the syntax pleasant), and an object instance for checking permissions.
The permissions framework I'm going to here, I think, is working fine and is not really part of my question. The difficulty that I am facing is
"Caught AttributeError while rendering: 'User' object has no attribute 'resolve'"
templatetags/permission_tags.py in render, line 23 (I've marked line 23 below)
, for . , , .
, templatetags/permission_tags.py
from django import template
register = template.Library()
def permission(parser, token):
try:
tag_name, username, permission, onkeyword, object = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires exactly 4 "
"arguments" % token.contents.split()[0])
nodelist = parser.parse(('endpermission',))
parser.delete_first_token()
return PermissionNode(nodelist, username, permission, object)
class PermissionNode(template.Node):
def __init__(self, nodelist, user, permission, object):
self.nodelist = nodelist
self.user = template.Variable(user)
self.permission = permission
self.object = template.Variable(object)
def render(self, context):
self.user = self.user.resolve(context)
self.object = self.object.resolve(context)
permissions_obj = self.object.permissions(self.user)
content = self.nodelist.render(context)
if hasattr(permissions_obj, self.permission):
perm_func = getattr(permissions_obj, self.permission)
if perm_func():
return content
return ""
register.tag('permission', permission)
- , , for, , ?
, , - . .
,