0

I want to run price_update() function on h6 element

{% for products in allProducts %}
<div class="col-6"> 
    Final Price: <h6 id="final_price_{{product.slug}}" onload="price_update({{products.price}},{{products.offer}}, {{product.slug}})"></h6>                                    
</div>

<script type="text/javascript">
function price_update(price, offer, slug) {
    let discounted_price = price- parseInt(price * offer / 100);
    let id = "final_price_" + String(slug);
    let f_price = document.getElementById(id);
    f_price.innerText = discounted_price;                                   
}
</script>
{% endfor %}

I got to know that onload cannot be used with <h6> . How can update innerText of <h6> for every product?

2 Answers 2

1

Create a custom template tag, do the arithmetic calculations there and, get the result :

  • In one of your apps create a new folder that is named templatetags
  • paste in the folder the __init__.py file to ensure the directory is treated as a Python package.
  • In templatetags folder, create a new module. This module is the one that would be loaded in your template. something like : myapp_extras.py
  • Import desired models (product) and then, add register = template.Library() to ensure the the module is a valid tag library
  • Register the custom filter by:

register the filter

@register.filter(name='price_update')
def price_update(product_id):
    # Get the product by id, and calculate the price
    
    # Return updated price

Load the module {% load myapp_extras %} in the template then, in your template use price_update tag:

<div class="col-6"> 
    Final Price: <h6 id="final_price_{{product.slug}}" >{{product.id|price_pudate}}</h6>                                    
</div>
Sign up to request clarification or add additional context in comments.

Comments

1
  1. Solution https://stackoverflow.com/a/63391216/14020019 by Amin Mir absolutely correct but I've implemented the solution in different way.

  2. My Solution : I've added property in my model

    @property
    def final_price(self):
        f_price = self.price - (self.price * self.offer // 100)
        return f_price
    

    using this I directly used the final_price using . operator, i.e. product.final_price

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.