我正在使用Django跟踪购物车中商品的总成本。我的问题是跟踪的第一个项目。当您扣除数量或减少数量时,价格会调整。但是低于它的任何东西都不会调整总成本。我认为问题是我没有错误地循环,所以经过几个小时的失败,我想我会问。
在
def cart()
我循环遍历成员变量添加更新
他们的价值观我遇到的问题是,当您点击book_id
cart()
传递给remove_from_cart
函数
但是,如果只传递了一个book_id
的问题,那么无论传递的book_id
是什么,只有购物车列表中的第一个项目才会被更改?
views.py
@login_required
def add_to_cart(request,book_id):
book = get_object_or_404(Book, pk=book_id)
cart,created = Cart.objects.get_or_create(user=request.user, active=True)
order,created = BookOrder.objects.get_or_create(book=book,cart=cart)
order.quantity += 1
order.save()
messages.success(request, "Cart updated!")
return redirect('cart')
def remove_from_cart(request, book_id):
if request.user.is_authenticated():
try:
book = Book.objects.get(pk = book_id)
except ObjectDoesNotExist:
pass
else:
cart = Cart.objects.get(user = request.user, active = True)
cart.remove_from_cart(book_id)
return redirect('cart')
else:
return redirect('index')
def cart(request):
if request.user.is_authenticated():
cart = Cart.objects.filter(user=request.user.id, active = True)
orders = BookOrder.objects.filter(cart=cart)
total = 0
count = 0
for order in orders:
total += order.book.price * order.quantity
count += order.quantity
context = {
'cart': orders,
'total': total,
'count': count,
}
return render(request, 'store/cart.html', context)
else:
return redirect('index')
答案 0 :(得分:1)
你的缩进稍微偏离了
def cart(request):
if request.user.is_authenticated():
cart = Cart.objects.filter(user=request.user.id, active = True)
orders = BookOrder.objects.filter(cart=cart)
total = 0
count = 0
for order in orders:
total += order.book.price * order.quantity
count += order.quantity
#Indentation needs to be offset by one level from here on
context = {
'cart': orders,
'total': total,
'count': count,
}
return render(request, 'store/cart.html', context)
else:
return redirect('index')