【发布时间】:2016-08-10 08:55:37
【问题描述】:
我正在尝试实现一个购物车,并创建了以下视图。前两个 cart_add(request, product_id) 和 cart_remove(request, product_id) 在会话中存储的购物车中添加和删除项目。然后他们每个人都重定向到cart_detail(request) 视图,该视图将购物车的当前内容返回到模板。
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
return redirect('cart:cart_detail')
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
return render(request, 'cart/detail.html', {'cart': cart})
我已将一些产品添加到购物车,但我得到的 json 如下所示:
{'product': '[{"model": "resource_manager.product", "pk": 6, "fields": {"created": "2016-04-17T12:33:43Z", "updated": "2016-04-18T10:45:17Z", "name": "Workbook", "image": "resource_manager/2016/04/18/20130405_171035.jpg"}}]', 'quantity': 12}
{'product': '[{"model": "resource_manager.product", "pk": 1, "fields": {"created": "2016-04-16T04:13:34Z", "updated": "2016-04-17T12:25:45Z", "name": "Radio", "image": ""}}]', 'quantity': 2}
{'product': '[{"model": "resource_manager.product", "pk": 2, "fields": {"created": "2016-04-16T11:15:57Z", "updated": "2016-04-17T12:25:45Z", "name": "Mat", "image": ""}}]', 'quantity': 9}
{'product': '[{"model": "resource_manager.product", "pk": 4, "fields": {"created": "2016-04-17T07:42:54Z", "updated": "2016-04-17T12:25:45Z", "name": "Tablet", "image": ""}}]', 'quantity': 3}
问题:如何访问模板cart/detail.html中每个产品的名称
这是我尝试过的:
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "resource_manager/img/no_image.png" %}{% endif %}">
</a>
</td>
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td><a href="{% url "cart:cart_remove" product.id %}">Remove</a></td>
</tr>
{% endwith %}
{% endfor %}
【问题讨论】:
标签: json django templates session cart