120

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.

daaawx
  • 3,273
  • 2
  • 17
  • 16
Tommy
  • 1,727
  • 3
  • 13
  • 9

3 Answers3

178

You can use the add filter:

{{ object.article.rating_score|add:"-100" }}
kyore
  • 812
  • 5
  • 24
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 45
    For multiplication and division you can misuse the built-in `widthratio` template tag. To compute a*b use `{% widthratio a 1 b %}`, for a/b use `{% widthratio a b 1 %}`. Only drawback, the results are rounded to an integer before returning. [Using Django’s widthratio template tag for multiplication & division](http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/) – elim Aug 03 '12 at 08:07
  • 2
    @Erik that should be its own answer - much better solution. – nhinkle Jan 28 '14 at 19:42
  • 2
    Updated link to [add](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#add) in the Docs – rnevius Apr 29 '15 at 09:57
  • What if I use like this : {{ object.article.rating_score|add:"{% widthratio object.article.rating_score 100 5 %}" }} – Mushahid Khan Sep 20 '16 at 17:39
  • @Daniel Roseman can I add after applying percentage like this: {{ object.article.rating_score|add:"{% widthratio object.article.rating_score 100 5 %}" }} – Mushahid Khan Sep 20 '16 at 17:40
  • Won't this result in `{{object.article.rating_score}} - 100` instead of `100 - {{object.article.rating_score}}`? If one renders this with `Template('{{ x|add:"-100" }}').render(Context({'x': 80}))`, I get `-20`, not `20`. – Willem Van Onsem Aug 21 '18 at 12:10
41

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

Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
Erik
  • 7,479
  • 8
  • 62
  • 99
21

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

bdd
  • 3,436
  • 5
  • 31
  • 43