Math Tags in Django Template Django.How

Author avatar wrote on 06/06/2022

Check difference > or <


 {% if x > 5 %} # You need some spaces

Show limited float fractions


 {{word_count_difference|floatformat:-2 }}
 

 

Way 1: Built-in widthratio template tag


    a*b use {% widthratio a 1 b %}
    a/b use {% widthratio a b 1 %}

 

Way 2: Template filters


from django import template

register = template.Library()

@register.filter
def multiply(value, arg):
    return value * arg

 

In template

{{ quantity | multiply:price }}

 

Way 3: Add the calculation as a function in your model!


Class LineItem:
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()
    price = models.DecimalField(decimal_places=2)

    def line_total(self):
        return self.quantity * self.price

 

In template

{{ line_item.line_total }}

 

Way 4: In view

Compute inside the view

Way 5: Use mathfilters library


{{ answer|mul:0.5 }}

 

Resources:
CRUDgen Django CRUD generator