Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading