I am trying to sell a basket with goods for an online store on django. The task is as follows: to store in the ID sessions of the goods and their quantity. If the goods are already in the basket, then the quantity is added to the old quantity (addition).
def post(self, request, **kwargs): post = request.POST item_id = int(post.get('id')) count = int(post.get('count')) if 'cart' not in request.session: request.session['cart'] = {} if item_id not in request.session['cart']: request.session['cart'][item_id] = count else: old = int(request.session['cart'][item_id]) request.session['cart'][item_id] = old + count print(request.session['cart']) return HttpResponse(json.dumps({'result': 'success'})) The problem is that when you add an existing product, one of the id is converted from a number to a string, because of which an existing product is added to the cart. It looks like this:
{4: 1, u'4': 1} #4 - id товара, 1 - его количество What is the problem?
print('before', request.session['cart'])before the lineif item_id not in request.session['cart']? While at first glance I don’t see any mistakes (except, let's say, stylistic, but more about that later) - andreymalint(..), then you fixed it, and forgot to clean the session, and thisu'4'probably remained from the old version of the code - andreymal sep('before', {}) {4: 1} [14/Sep/2017 13:22:09] "POST /ajax/addtocart/ HTTP/1.1" 200 20 ('before', {u'4': 1}) {4: 3, u'4': 1}- Eduard Design