I’m trying to pass a variable from the URL (not the query string) to a custom tag, but it looks like I’m getting a ValueError when converting it to an int. It appears at first glance that it’s coming in as a string like “project.id” instead of the actual integer value of that. From what I understand, the tag parameters are always strings. If I print out the value of the parameter in my view before sending it down, it appears correct. It might just be a string, but I figured that shouldn’t matter if the template is going to convert it to an int anyway, right?
# in urls.py
# (r'^projects/(?P<projectId>[0-9]+)/proposal', proposal_editor),
# projectId sent down in RequestContext as 'projectId'
# in template
# {% proposal_html projectId %}
# in templatetag file
from django import template
register = template.Library()
@register.tag(name="proposal_html")
def do_proposal_html(parser, token):
try:
# split_contents() knows not to split quoted strings.
tagName, projectId = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
print(projectId)
projectId = int(projectId)
return ProposalHtmlNode(int(projectId))
class ProposalHtmlNode(template.Node):
def __init__(self, projectId):
self.projectId = projectId
The issue is simply that you haven’t resolved the variables to the values they contain. If you put some logging into your method, you’ll see that at that point
projectIdis actually the string"projectId", because that’s how you referenced it in the template. You need to define this is an instance oftemplate.Variableand then resolve it in theNode‘srendermethod. See the documentation on resolving variables.However, depending on what you’re actually doing in
render, you may find it easier to get rid of the Node class altogether and just use thesimple_tagdecorator, which as well as not needing a separate Node also gets the variables already resolved as its parameters.