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
No comments:
Post a Comment