[Django]-Is there a filter for divide for Django Template?

94๐Ÿ‘

โœ…

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

34๐Ÿ‘

  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

15๐Ÿ‘

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 }}

6๐Ÿ‘

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.

0๐Ÿ‘

Instead of having the percentage already calculated like in your question, you can use this tag to calculate the percentage in the template from the original value and total value against which your percentage is calculated. It does the job if you only need an integer percentage without precision:

{% widthratio value total_value 100 %}

Ref: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#widthratio

-2๐Ÿ‘

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

Leave a comment