Tommy
Tommy

Reputation: 1767

How to do math in a Django template?

I want to do this:

100 - {{ object.article.rating_score }} 

So for example, the output would be 20 if {{ object.article.rating_score }} equaled 80.

How do I do this at the template level? I don't have access to the Python code.

Upvotes: 124

Views: 133700

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You can use the add filter:

{{ object.article.rating_score|add:"-100" }}

Upvotes: 186

Erik
Erik

Reputation: 7751

Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value.

For the specific example above, you would use {{ 100|sub:object.article.rating_score }}.

Upvotes: 42

bdd
bdd

Reputation: 3434

Generally it is recommended you do this calculation in your view. Otherwise, you could use the add filter.

Upvotes: 21

Related Questions