【发布时间】:2018-12-19 14:47:37
【问题描述】:
我想计算模板中购物车的总数: 这是我的带有产品表的模板。 我尝试在我的购物车方法中使用生成器表达式,但它不起作用。 有什么想法吗?
cart.html
<table>
{% if not cart_list %}
{{ "The cart is empty" }}
{% else %}
<tr>
<th>Name</th>
<th>Price</th>
</tr>
{% for product in cart_list %}
<tr>
<td>{{ product.name }}</td>
<td>${{ product.price }}</td>
</tr>
{% endfor %}
<tr>
<td>{{ Total }}</td>
<td>{{ total_prices }}</td>
</tr>
{% endif %}
</table>
views.py
def cart(request):
if request.method == 'GET':
cart_list = Product.objects.filter(in_cart = True)
total_prices = sum(product.price for product in cart_list)
template_cart = loader.get_template('cart/cart.html')
context = {'cart_list': cart_list}
return HttpResponse(template_cart.render(context, request))
【问题讨论】:
-
您需要将
total_prices添加到您的上下文对象中,以便可以从模板页面访问它。 -
感谢您的快速回复!
标签: python django django-templates sum generator-expression