Cian
Cian

Reputation: 1629

Django Session Not Working - New Cart For Each Item

I'm working on a simple e-commerce site (following the Coding for Entrepreneurs course). I have view for the cart (below). I'm having a problem with the session - each time I add an item to the cart it gets added to a new cart, when they should be all added to the same cart for that session. I'm new to Django, and can't see where I'm going wrong here. Any advice on how to get each item added to go into the same cart would be much appreciated.

# 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

Upvotes: 0

Views: 1481

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55207

Don't catch the generic Exception, catch the specific KeyError you're looking for.

Here, you'll get a TypeError because cart_id = request.session('cart_id') should use [] and not (). You're therefore entering your except clause, causing you to create a new cart when you didn't mean to.

You should do:

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

But anyway, is the cart not existing really an "exceptional" condition? Probably not. So you might want to do:

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

You probably should be checking the Cart actually exists, too.

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

And just use cart from then on.

Upvotes: 2

Related Questions