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
太好了,非常感謝,真的很有幫助! 我現在看到 'ValueError異常在/車/ add' '無法分配無:「CartItem.cart」不允許空values.' 我猜是從我的表單來的? – Cian
查看代碼:當您嘗試從數據庫中檢索購物車時,您有另一個「except Exception」子句。輸入該子句會導致「購物車」爲「無」。與您會話中的ID相對應的購物車可能不存在於數據庫中。你正在尋找的例外是'Cart.DoesNotExist'。 –
不錯,我現在看到了。爲此歡呼,爲我澄清事情! – Cian