'I want to calculate percentage in template with django

I want to calculate and show the discount interest of the product in the template. I tried something like below but it didn't work. Is there a practical way to do this?

index.html

{% if product.sale %}
<span class="sale">{{((product.price - product.sale) / product.price) * 100}}</span>
{% endif %}


Solution 1:[1]

You don't. Such logic does not belong in the template. Django's template language is deliberately restricted to prevent people from writing this logic in the template.

Usually you write this in the model, for example as a propertly, like:

class Product(models.Model):
    # …
    
    @property
    def price_percentage(self):
        return 100 * (self.price - self.sale) / self.price

then in the template you can render this as:

{% if product.sale %}
    <span class="sale">{{ product.price_percentage }}</span>
{% endif %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem