How to do math in a Django template?

PythonDjangoDjango Templates

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

You can use the add filter:

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

Solution 2 - Python

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

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTommyView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonErikView Answer on Stackoverflow
Solution 3 - PythonbddView Answer on Stackoverflow