【发布时间】:2021-06-01 00:18:55
【问题描述】:
我想在我的购物车模板中显示一些商品,但它什么也没显示。
当我不使用for 循环时,它可以正常工作,但当我将它用于循环时,它什么也没显示。
我的猜测是,我的 Cart 课程可能有问题,我不确定,但如果你检查一下就好了。
查看:
from django.shortcuts import render, get_object_or_404, redirect
from Products.models import Product
from .forms import AddCartForm
from django.views.decorators.http import require_POST
from decimal import Decimal
CART_SESSION_ID = 'cart'
class Cart:
def __init__(self, request):
self.session = request.session
cart_session = self.session.get(CART_SESSION_ID)
if not cart_session:
cart_session = self.session[CART_SESSION_ID] = {}
self.cart = cart_session
def add_product(self, product, quantity):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session.modified = True
def __iter__(self):
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['total_price'] = Decimal(item['price']) * item['quantity']
yield item
@require_POST
def add_product(request, product_id):
cart = Cart(request)
form = AddCartForm()
if form.is_valid():
product = get_object_or_404(Product, pk=product_id)
quantity = form.cleaned_data['quantity']
cart.add_product(product=product, quantity=quantity)
return redirect('cart:cart_details')
def cart_details(request):
cart = Cart(request)
context = {'cart': cart}
return render(request, 'cart/cart_details.html', context=context)
模板:
<table class="table table-condensed">
<head>
<tr class="cart_menu">
<td class="image">Item</td>
<td class="description"></td>
<td class="price">Price</td>
<td class="quantity">Quantity</td>
<td class="total">Total</td>
<td></td>
</tr>
<body>
<tr>
{% for item in cart %}
<td class="cart_description">
********HERE I CAN NOT SEE THE PROUDUCT NAME OR PRICE AND ...*******
<h4><a href="#">TEST{{ item.product }}</a></h4>
<p>{{ item.price }}</p>
</td>
{% endfor %}
</tr>
</tbody>
</table>
模板图片
P.S : 我解决了这个问题并将其发布在下面。
【问题讨论】:
-
当你
print(cart)在视图中时,它在吗? -
@dacx 感谢您的回复,是的,在“def add_product”和“def cart_details”中我可以看到“details
”,但我在“def iter”,什么也不显示,在“def init”中也每次显示一个空白字典,即使我增加了产品的数量 -
我在几天前看到了你同样的问题。这不是真正可以回答的:它需要调试,它只包含解决方案的一部分,它基于 specific 解决方案,除了请求之外不存储卡(我在这方面是否正确?)。
When I don't use a for loop, it works fine请详细说明。如果没有for loop,这个模板只包含静态文本,那么什么“工作正常”? -
@IvanStarostin:我的朋友,我解决了这个问题,感谢您的关注和评论。
标签: python python-3.x django django-views django-templates