【发布时间】:2018-11-20 01:24:26
【问题描述】:
所以基本上在我的商店里,每件商品都有特定的重量,一旦客户添加了他们想要的任何东西并去结账,他们就可以看到他们的每一个订单以及名称信息和重量。我还想把所有物品的总重量加在一起。目前,它仅显示每个特定项目的重量。
例如
这是我的意见.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))
return render(request, template_name, {'order_details': order_details, 'current_order': current_order})
这是我的模板
<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>
【问题讨论】:
-
您定义了一个
total_weight变量但没有使用它;为什么不在 for 循环中将每个weight添加到它,然后将该变量发送到模板? -
@Danel Roseman 我不确定如何计算它。项目中的项目:total_weight = total_weight + item.supplyID.weight * item.quantity 工作?正如我所做的那样,然后我尝试添加
{{total_weight}}
并且它似乎没有工作 -
但是您已经为每次迭代计算了
weight。只需在该循环内执行total_weight += weight。并且不要忘记在您的render调用中将其添加到模板上下文中。