Documentation
传递给render的上下文变量必须是字典,因此可以在views.py中计算总权重,将该值放入字典中,然后在模板中获取总权重键的值。
例如:
def checkout(request):
try:
current_order = Order.objects.filter(owner=1).get(status="pre-place")
except Order.DoesNotExist:
return HttpResponse("Your current order is empty<br><a href=\"browse\">Go back</a>")
else:
total_weight = 0
items = OrderDetail.objects.filter(orderID=current_order)
template_name = 'store/checkout.html'
order_details = []
for item in items:
weight = item.supplyID.weight * item.quantity
order_details.append((item, weight))
total_weight +=weight
return render(request, template_name, {'order_details': order_details, 'current_order': current_order, 'Total Weight' : total_weight})
然后在模板中使用该变量:
<h1>Your current order</h1>
<a href="{% url 'Store:browse' %}">return to selecting supplies</a><br><br>
<table>
<tr>
<th>name</th><th>item weight(kg)</th><th>qty</th><th>total weight(kg)</th>
</tr>
{% for order_detail, weight in order_details %}
<tr>
<td>{{ order_detail.supplyID.name }}</td>
<td>{{ order_detail.supplyID.weight }}</td>
<td>{{ order_detail.quantity }}</td>
<td>{{ weight }}</td>
</tr>
{% endfor %}
</table>
<p>The total weight of your order is:</p>
<p>{{Total Weight}}</p>