2013-08-21 101 views
0

我正在研究一個簡單的電子商務網站(遵循Coding for Entrepreneurs課程)。我有購物車的意見(見下文)。我在會話中遇到問題 - 每次我將商品添加到購物車時,都會將其添加到新購物車,但應該全部添加到該會話的同一購物車中。我是Django的新手,無法看到我在哪裏出錯。任何關於如何讓每個物品添加到相同的購物車的建議將非常感激。Django會話不工作 - 每個項目的新購物車

# imports 

def add_to_cart(request): 
    try: 
     cart_id = request.session('cart_id') 
    except Exception: 
     # If cart_id doesn't exist, make one 
     cart = Cart() 
     cart.save() 
     request.session['cart_id'] = cart.id 
     cart_id = cart.id 

    # If adding to the cart, need to POST 
    if request.method == "POST": 
     # Get data from the form 
     form = ProductQtyForm(request.POST) 
     if form.is_valid(): 
      product_slug = form.cleaned_data['slug'] 
      product_quantity = form.cleaned_data['quantity'] 
      # Use that info to set up new objects in our cart 
      try: 
       product = Product.objects.get(slug=product_slug) 
      except Exception: 
       product = None 
      try: 
       cart = Cart.objects.get(id=cart_id) 
      except Exception: 
       cart = None 
      new_cart = CartItem(cart=cart, product=product, quantity=product_quantity) 
      new_cart.save() 
      print new_cart.product, new_cart.quantity, new_cart.cart # Check items are being added to the cart 
      return HttpResponseRedirect('/products/') 
     # If form is not valid, go to contact page 
     return HttpResponseRedirect('/contact/') 
    else: 
     raise Http404 

回答

2

不要捕捉通用Exception,抓住你正在尋找的特定KeyError

在這裏,您將獲得TypeError,因爲cart_id = request.session('cart_id')應該使用[]而不是()。因此,您正在輸入您的except條款,導致您創建新的購物車時,你不打算。

你應該這樣做:

try: 
    cart_id = request.session['cart_id'] # Fix this 
except KeyError:       # Fix that 
    # If cart_id doesn't exist, make one 
    cart = Cart() 
    cart.save() 
    request.session['cart_id'] = cart.id 
    cart_id = cart.id 

但是,無論如何,是不存在一個真正的「例外」條件下的車?可能不會。所以你可能想這樣做:

cart_id = request.session.get('cart_id') 

if cart_id is None: 
    cart = Cart.objects.create() 
    cart_id = cart.id 
    request.session['cart_id'] = cart.id 

你可能應該檢查車實際上也存在。

carts = Cart.objects.filter(pk=request.session.get('cart_id')) 
# I'm not fully sure None is accepted here, use -1 if it's not. 

if carts: 
    cart = carts[0] 
else: 
    cart = Cart.objects.create() 
    request.session['cart_id'] = cart.id 

並且從此使用cart

+0

太好了,非常感謝,真的很有幫助! 我現在看到 'ValueError異常在/車/ add' '無法分配無:「CartItem.cart」不允許空values.' 我猜是從我的表單來的? – Cian

+1

查看代碼:當您嘗試從數據庫中檢索購物車時,您有另一個「except Exception」子句。輸入該子句會導致「購物車」爲「無」。與您會話中的ID相對應的購物車可能不存在於數據庫中。你正在尋找的例外是'Cart.DoesNotExist'。 –

+0

不錯,我現在看到了。爲此歡呼,爲我澄清事情! – Cian