I have this page that lists various info on a specific stock including orders that have been placed on that specific item. I would like to display how much money the user of this system would get from that specific order.
<table class='table'>
<thead>
<tr>
<th>ORDER ID</th>
<th>NAME</th>
<th>AMOUNT ORDERED</th>
<th>REVENUE</th>
<th>ORDERED ITEM</th>
<th>ADDRESS</th>
<th>CITY</th>
</tr>
</thead>
{% for x in queryset2 %}
<tr>
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>{{x.quantity}}</td>
<td>{{x.quantity * stock.ppu}}</td>
<td>{{x.order_item}}</td>
<td>{{x.address}}</td>
<td>{{x.city}}</td>
</tr>
{% endfor %}
</table>
I have this code so far. What would be the correct syntax to multiply these two variables together : {{x.quantity * stock.ppu}}
CodePudding user response:
You can not write arithmetic expressions in a Django template. You should write this in the view, for example by annotating the queryset:
from django.db.models import F
# …
queryset2 = queryset2.annotate(
total_value=F('quantity') * F('ppu')
)
then in the template you render this as:
<td>{{ x.total_value }}</td>
CodePudding user response:
To do math operations in the Django template you can use this django-mathfilters
but if you try to use a built-in way to do, can follow this to add and Subtraction
Example:
{{x.quantity | add: stock.ppu}}
to do multiplication and division you can use widthratio
Example:
a*b use {% widthratio a 1 b %}
a/b use {% widthratio a b 1 %}
from this answer
or you can make your own custom tags
for add
@register.filter
def add_value(value, arg):
return value arg
for subtract
@register.filter
def subtract(value, arg):
return value - arg
then use them in your template like this
{{x.quantity | subtract: stock.ppu}}