0

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

1 回答 1

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从那时起使用。

于 2013-08-21T17:53:13.057 回答