我正在开发一个简单的电子商务网站(遵循企业家编码课程)。我有购物车的视图(下)。我在会话中遇到问题 - 每次我将一个项目添加到购物车时,它都会被添加到一个新的购物车中,而此时它们应该都被添加到该会话的同一个购物车中。我是 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