Is there a filter for divide for Django Template?

Question:

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

||

Answers:

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

http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/

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/__init__.py
  2. Create a module within templatetags with the following code:
# my_app/templatetags/my_custom_filters.py
from django import template

register = template.Library()

@register.filter
def divide(value, arg):
    try:
        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 https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/ 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 %}

Syntax:

{% 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.