Django Template : How To Perform Mathematical Operations In Django Templates

Dec 3 2022 . 3 min read
unsplashimagePhoto by Lucas K on Unsplash

Django Template is a very powerful template engine, that make your simple static content into dynamic content.

But when i was working one of my project in django, where i had had to perform some mathematical opertions like additon, substractions etc. i didn't find any operators like (+ , - , *, /) in django template just like jinja.

So, here we will going to see all the ways to perform mathematical opertions in django template.

Ways to perform mathematical opertions

There multiple ways to perform mathematical operation in django templates, but we will see only two ways here :

  1. Using view function (Hard coded)
  2. Using django-mathfilters (Third party package)

1. Using view function (Hard coded)

So, here in view function we can perform the operations using the operators which we have in python and pass throught the context and can be use in our template file.

views.py
  1. from django.shortcuts import render
  2. def index(request):
  3.     a = 10, b = 20
  4.     add = a + b
  5.     sub = a - b
  6.     mul = a * b
  7.     div = a / b
  8.     return render(request, 'index.html', {'add' : add, 'sub' : sub, 'mul' : mul, 'div' : div, 'a' : a, 'b' : b})
index.html
  1. <html>
  2.     <body>
  3.          Addition of {{ a }} and {{ b }} is {{ add }}
  4.          Subtraction of {{ a }} and {{ b }} is {{ sub }}
  5.          Multiplication of {{ a }} and {{ b }} is {{ mul }}
  6.          Division of {{ a }} and {{ b }} is {{ div }}
  7.     </body>
  8. </html>

2. django-mathfilters (Third party package)

django-mathfilters is an awesome package that gives you a functionality to perform mathematical operations directly in your django templates.


Before to use first need to install that package using this command -

pip install django-mathfilters

Now we have to add mathfilters to INSTALLED_APPS.

Next we need to load mathfilters at the top of the template. The script provides the following filters:

  1. sub - subtraction
  2. mul - multiplication
  3. div - division
  4. intdiv - integer (floor) division
  5. abs - absolute value
  6. mod - modulous
  7. addition - replacement for the add filter with support for float / decimal types


Let's implement operations directly in our template file.

index.html
  1. {% load mathfilters %}
  2. <html>
  3.     <body>
  4.          Addition of 8 + 3 is {{ 8|addition:3 }}
  5.          Substraction of 8 - 3 is {{ 8|sub:3 }}
  6.          Multiplication of 8 * 3 is {{ 8|mul:3 }}
  7.          Divison of 8 / 3 is {{ 8|div:3 }}
  8.     </body>
  9. </html>

Conclusion

That's all. In this tutorial we have discussed a ways to perform mathematical operations in django templates. You can bulid your own custom templates tags and filters for mathematicals operation.