Django会话不工作 - 每个项目的新推车

时间:2013-08-21 17:48:31

标签: python django django-views

我正在开发一个简单的电子商务网站(遵循Coding for Entrepreneurs课程)。我有购物车的视图(下方)。我遇到了会话问题 - 每次我将一个项目添加到购物车时,它会被添加到新购物车中,当它们全部添加到该会话的同一购物车中时。我是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

1 个答案:

答案 0 :(得分: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