2016-03-22 13 views
0

私はDjangoでショッピングカートのアイテムの総コストを追跡しています。私の問題は、最初のアイテムが追跡されることです。数量を減じたり量を減らしたりすると、価格が調整されます。しかし、それ以下のものは総コストを調整しません。私は問題は私がそれを間違ってループしていないと思うので、何時間も失敗すると私は尋ねると思った。Djangoのショッピングカートでアイテムを更新する

def cart() 

では、私は その値を更新するメンバ変数を通じてaddがループしています。私が直面しています問題は、あなたが remove_from_cart

をクリックしたときにのみbook_idcart()関数に渡されていることである。しかし、それは唯一の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') 

答えて

1

あなたのインデントは、OMG ...あなたはこのようなボスですわずか

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') 
+0

オフです。これは私に何時間もの悲しみをもたらしました。私のリンターはどうやってこれをキャッチできないの?これを避けるにはどうすればいいですか? – wuno

+0

これらは残念ながら流れを論理的に理解することによってしか捕らえられません。デバッグするには、print文を使うか、 'pdb'を使う方法があります。 – karthikr

+0

ありがとうございました。私はそれを見るでしょう。 – wuno

関連する問題