Home > Software engineering >  I want to calculate percentage in template with django
I want to calculate percentage in template with django

Time:03-28

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 >{{((product.price - product.sale) / product.price) * 100}}</span>
{% endif %}

CodePudding user response:

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 >{{ product.price_percentage }}</span>
{% endif %}
  • Related