Is there a filter for divide for Django Template?

前端 未结 6 1870
囚心锁ツ
囚心锁ツ 2020-12-20 11:01

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.

相关标签:
6条回答
  • 2020-12-20 11:18

    Using a custom filter:

    register = template.Library()
    
    @register.filter
    def divide(value, arg):
        try:
            return int(value) / int(arg)
        except (ValueError, ZeroDivisionError):
            return None
    
    0 讨论(0)
  • 2020-12-20 11:21

    Check out http://djangosnippets.org/snippets/2424/

    Hope that helps you out.

    0 讨论(0)
  • 2020-12-20 11:31

    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 讨论(0)
  • 2020-12-20 11:34

    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

    0 讨论(0)
  • 2020-12-20 11:35

    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 }}
    
    0 讨论(0)
  • 2020-12-20 11:43

    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

    0 讨论(0)
提交回复
热议问题