Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 241
Tommy Avatar asked Jun 08 '11 21:06

Tommy


People also ask

How do you use math operation in Django template?

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.


2 Answers

You can use the add filter:

{{ object.article.rating_score|add:"-100" }} 
like image 116
Daniel Roseman Avatar answered Sep 19 '22 13:09

Daniel Roseman


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 }}.

like image 38
Erik Avatar answered Sep 21 '22 13:09

Erik