I’m trying to get a custom template tag to work but am having some difficulties when I apply the tag within a for loop with multiple items in the thing being iterated across.
I’d like to have the tag look as below and only display the text “WORKED” if my permissions function evaluates to True.
Template code
{% load permission_tags %}
{% for group in groups %}
<div>{% permission request.user can_edit_group on group %}WORKED{% endpermission %}</div>
{% endfor %}
The tag basically takes in a user instance, a permissions string (i.e. “can_edit_group”), an “on” keyword (just to make the syntax nice) and an object instance to check permissions on.
The permissions framework I have going here I think is working ok and is not really part of my question. The difficulty I am having 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)
template error when the for loop contains more than one group. The tag works nicely with just one group, but bombs out if I add more than one.
Template tag called permissions in 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) # <---- Line 23
self.object = self.object.resolve(context)
# My custom permissions code. I don't think it's
# causing the error I am experiencing
permissions_obj = self.object.permissions(self.user)
content = self.nodelist.render(context)
# My custom permissions code. I don't think it's causing
# the error.
if hasattr(permissions_obj, self.permission):
perm_func = getattr(permissions_obj, self.permission)
if perm_func():
return content
return ""
register.tag('permission', permission)
Do you have any idea why this template tag generates an error when I have more than one item in my for loop but succeeds when I have just one?
I don’t quite yet understand all of the inner-workings of this template tags syntax, so I have a feeling I have made a logic error somewhere. Any advice is much appreciated.
Thank you,
Joe
When you change back
self.userto aUserinstance here:it works the first time, but the next time, because
self.useris no longer atemplate.Variableinstance, you get the exception: ‘User’ object has no attribute ‘resolve'”One solution is to save
user&objectinstance in local variables: