I want to show sum of subtotal in my template.
{% for quote in quotes %}
{% for product in quote.purchase_quote_products_set.all %}
{{product.subtotal}} |
{% endfor %}
<span id="total"></span>
{% endfor %}
my result.
15 | 120 | 2000 |
Is there any way to show sum of subtotal inside span#total
<span id="total">{{ sum_of_subtotal }}</span>
It is best to perform such arithmetic in Django views rather than templates. For e.g. you can find the sum in the view itself:
from django.db.models import Sum
total_price = Quotes.objects.all().annotate(total=Sum('purchase_quote_products__subtotal'))
Then the template can use:
<span id="total">{{ quote.total }}</span>
If you are trying to calculate on the template, then in Django Template there is something called filter which are use to alter values of variables before they’re render to UI.
Custom filters are just Python functions that take one or two arguments:
Filter functions should always return something. They shouldn’t raise exceptions. They should fail silently. In case of error, they should return either the original input or an empty string – whichever makes more sense.
Here’s an example filter definition:
def cut(value, arg):
"""Removes all values of arg from the given string"""
return value.replace(arg, '')
And here’s an example of how that filter would be used:
{{ somevariable|cut:"0" }}
Please read the following docs for more information, custom_template
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With