I am creating an eCommerce store and I use Django sessions to store the cart information. However, for some reason, only 2 items get stored in the cart and no more. Once I add the first item, it stays there as it is. Then I add the 2nd item. However, when I add the 3rd item, the 2nd item is overwritten by the 3rd one, still keeping only 2 products in the cart.
I feel it would be a simple logic error but I can't seem to figure it out.
My views.py...
def shop(request):
if not request.session.get('order1'):
request.session['order1'] = []
if request.method == "POST":
quantity = int(request.POST.get('quantity'))
name = request.POST.get('name')
if quantity >= 1:
request.session.get('order1').append({"quantity":quantity, "name":name})
context = {
"check":request.session.get('order1'),
}
else:
messages.warning(request, "You have entered an invalid quantity")
context={}
else:
context={}
return render(request, "store/shop.html", context)
And the output of the context = {"check":request.session.get('order1')}
is something like this [{'quantity': 1, 'name': 'Tissot Watch for men - black star striped'}, {'quantity': 2, 'name': 'Jewelry Bangles Stripes for Girls'}]
and always stays with only 2 items.
Is there any error in the code that I have done?
Any help would be greatly appreciated. Thanks!
Since request.session['order1']
is a list any changes to it will not be detected as "changes" by the session middleware since it is still the same object.
One solution is to set the modified
attribute on the session
# In your view after appending to a list in the session
request.session.modified = True
Another solution to this is to update your settings to save the session on every request regardless of if the middleware thinks it's been changed or not
# In settings.py
SESSION_SAVE_EVERY_REQUEST = True