Can I perform calculations directly in django tags/filters?

6,387 views
Skip to first unread message

jago

unread,
Nov 18, 2008, 2:55:40 PM11/18/08
to Django users
I am thinking about something like {{ (width - 5) *12 }} ?

Rajesh Dhawan

unread,
Nov 18, 2008, 3:26:45 PM11/18/08
to Django users
> I am thinking about something like {{  (width - 5) *12  }}  ?

No. That syntax is not supported in Django templates.

DavidA

unread,
Nov 18, 2008, 5:19:12 PM11/18/08
to Django users
You can do it in a custom eval-like tag:

@register.tag()
def evalpy(parser, token):
try:
tag_name, expression = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a
single argument" % token.contents.split()[0]
if not (expression[0] == expression[-1] and expression[0] in
('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument
should be in quotes" % tag_name
return EvalNode(expression[1:-1])

class EvalNode(template.Node):
def __init__(self, expression):
self.expression = expression
def render(self, context):
return eval(self.expression, {}, context)

and then use it like below. Note you can access context/template
variables this way:

{% get_comment_count for post as comment_count %}
<h1>{% evalpy "comment_count + 3" %}</h1>

Kludgy, yes, but sometimes useful.
-Dave

Daniel Roseman

unread,
Nov 18, 2008, 5:21:09 PM11/18/08
to Django users
On Nov 18, 7:55 pm, jago <java.j...@gmail.com> wrote:
> I am thinking about something like {{  (width - 5) *12  }}  ?

No. You can add or subtract using the 'add' filter:
{{ width:add:"-5" }}
but anything else will require a custom template tag or filter.
Luckily, these are extremely easy to write:

@register.filter
def multiply(value, arg}
return int(value) * int(arg)

{{ width|multiply:12 }}

You'll want to add error checking and so on of course, but that's the
idea.

--
DR.

Adeotun Adegbaju

unread,
Dec 18, 2019, 5:55:52 PM12/18/19
to Django users
you should indicate which files codes should be added to

Luqman Shofuleji

unread,
Dec 18, 2019, 6:00:37 PM12/18/19
to django...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3b901f38-024c-47b6-9794-c116b6d9913c%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages