Problem with a token in my custom template tag

21 views
Skip to first unread message

Daniel Grace

unread,
Oct 15, 2014, 2:30:01 PM10/15/14
to django...@googlegroups.com
Hi,
I'm encountering the following problem with a token in my custom template tag:
Request Method: GET
Django Version: 1.7
Exception Type: ValueError
Exception Value:
need more than 2 values to unpack
Exception Location: C:\landy\cresta\flow\templatetags\flow_extras.py in rowcolour, line 7

Here is the template file:
from django import template
from datetime import datetime, timedelta
register = template.Library()

@register.tag
def rowcolour(parser, token):
nm, dt, fmt = token.split_contents() # this is line 7
diff = datetime.now() - dt
if diff.days > 14:
return "pinkrow"
else:
return "greyrow"

... here is the line in the html file:
<tr id="{% rowcolour flow.created %}">

... and "created" is defined as follows in the model:
created = models.DateTimeField(db_index=True, auto_now_add=True)

I'm trying to extract the datetime from the token.  Any ideas?

Thanks.

Daniel Roseman

unread,
Oct 15, 2014, 3:08:55 PM10/15/14
to django...@googlegroups.com
Like the error says, you are telling it to split the result of `token.split_contents()` into three variables, but you are only passing it two elements: "rowcolour" and "flow.created". Where is `fmt` supposed to be coming from?

However, even when you fix that, this still won't work, as at that point `dt` will just be the string "row.created". You need to have a whole template Node in order to resolve variables like that. Why are you not using the `simple_tag` decorator, which is a shortcut for that whole process?

@register.simple_tag
def rowcolour(dt):
diff = datetime.now() - dt
...etc...

--
DR.

Daniel Grace

unread,
Oct 15, 2014, 3:38:10 PM10/15/14
to django...@googlegroups.com
I got it working thanks.  My template tag file is as follows:

from django import template
from django.utils import timezone
register = template.Library()

@register.simple_tag
def rowcolour(dt):
diff = timezone.now() - dt
Reply all
Reply to author
Forward
0 new messages