Reputation: 9875
I am tracking the total cost of items in a shopping cart with Django. My problem is the first item is tracked. When you deduct quantity or reduce quantity the price adjust. But anything that is below it does NOT adjust the total cost. I think the problem is I am not looping through it incorrectly so after many hours of failure I figured I would ask.
In
def cart()
I am looping through the member variables add updating
their values. The problem I am facing is that only the book_id
is being passed to the cart()
function when you click remove_from_cart
But if it was a problem of only one book_id
being passed in then how come only the first item in the cart list is being changed regardless of the book_id
that is being passed in?
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')
Upvotes: 0
Views: 1489
Reputation: 99640
Your indentation is slightly off
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')
Upvotes: 1