Django Mathfilters
django-mathfilters is a Python 3 module that provides a set of simple mathematical template filters for Django. It extends Django's built-in 'add' filter by offering operations like subtraction, multiplication, division, integer division, absolute value, and modulo. It supports 'int', 'float', and 'Decimal' types, allowing for basic arithmetic directly within templates. The current version is 1.0.0, and it serves as a stable utility for common math operations not natively supported by Django's template language.
Warnings
- breaking In versions prior to 0.4.0, the 'addition' filter might not have been available or behaved differently, causing 'TemplateSyntaxError'.
- gotcha Values passed to math filters must be compatible numeric types (int, float, or Decimal). Passing non-numeric values (e.g., strings that cannot be converted) will likely result in a runtime error or an empty string output in the template.
- gotcha Forgetting to add 'mathfilters' to your `INSTALLED_APPS` in `settings.py` will prevent the template tags from being recognized, leading to a `TemplateSyntaxError` for 'mathfilters' not being a registered tag library.
Install
-
pip install django-mathfilters
Imports
- mathfilters
{% load mathfilters %}
Quickstart
{% load mathfilters %}
<p>Subtraction: {{ 10|sub:3 }}</p>
<p>Multiplication: {{ 5|mul:2.5 }}</p>
<p>Division: {{ 10|div:4 }}</p>
<p>Integer Division: {{ 10|intdiv:4 }}</p>
<p>Absolute Value: {{ -7|abs }}</p>
<p>Modulo: {{ 10|mod:3 }}</p>
<p>Addition (float/decimal support): {{ 5.5|addition:2.3 }}</p>