Django Template : How To Perform Mathematical Operations In Django Templates
Table of Content
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 :
- Using view function (Hard coded)
- 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.
- from django.shortcuts import render
- def index(request):
- a = 10, b = 20
- add = a + b
- sub = a - b
- mul = a * b
- div = a / b
- return render(request, 'index.html', {'add' : add, 'sub' : sub, 'mul' : mul, 'div' : div, 'a' : a, 'b' : b})
- <html>
- <body>
- Addition of {{ a }} and {{ b }} is {{ add }}
- Subtraction of {{ a }} and {{ b }} is {{ sub }}
- Multiplication of {{ a }} and {{ b }} is {{ mul }}
- Division of {{ a }} and {{ b }} is {{ div }}
- </body>
- </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 -
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:
- sub - subtraction
- mul - multiplication
- div - division
- intdiv - integer (floor) division
- abs - absolute value
- mod - modulous
- addition - replacement for the add filter with support for float / decimal types
Let's implement operations directly in our template file.
- {% load mathfilters %}
- <html>
- <body>
- Addition of 8 + 3 is {{ 8|addition:3 }}
- Substraction of 8 - 3 is {{ 8|sub:3 }}
- Multiplication of 8 * 3 is {{ 8|mul:3 }}
- Divison of 8 / 3 is {{ 8|div:3 }}
- </body>
- </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.