Is there a filter for divide for Django Template?


I noticed there is built-in add filter, but I wasn’t able to find divide.

I am new to Django and not sure if there is a such filter.

Asked By: Sam



There is not it. But if you are a little hacker….

to compute A*B: {% widthratio A 1 B %}

to compute A/B: {% widthratio A B 1 %}

to compute A^2: {% widthratio A 1 A %}

to compute (A+B)^2: {% widthratio A|add:B 1 A|add:B %}

to compute (A+B) * (C+D): {% widthratio A|add:B 1 C|add:D %}

Also you can create a filter to division in 2 minutes

Answered By: Goin
  1. Create a templatetags package within your Django app: my_app/templatetags/
  2. Create a module within templatetags with the following code:
# my_app/templatetags/
from django import template

register = template.Library()

def divide(value, arg):
        return int(value) / int(arg)
    except (ValueError, ZeroDivisionError):
        return None
  1. In your template, add the following, replacing my_custom_filters with the module name in step 2:
{% load my_custom_filters %}

{{ 100|divide:2 }}

See for more information

Answered By: sidarcy

I would use a custom template, but if you don’t want to you can use the widthratio built in tag,

{% widthratio request.session.get_expiry_age 3600 1 %} 

Another example

{% widthratio value 1150000 100 %}


{% widthratio parm1 parm2 parm3 %}

So basically its used for scaling images, but you can use it for division. What it does is: parm1/parm2 * parm3.

Hope this helps, more on widthratio here.

Answered By: radtek

There is a Python module to do math operations in your templates: Django-Mathfilters.

It contains add as you said, but also div to divide:

 8 / 3 = {{ 8|div:3 }}
Answered By: guhur

You can use divisibleby

Returns True if the value is divisible by the argument.

For example:

{{ value|divisibleby:"3" }}

If value is 21, the output would be True.

You can see django docs

Answered By: Mohammad Reza
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.