Search code examples
pythondjangosessioncartdjango-sessions

django manipulate session(insert,update,...)


i want to add product's ref_id in cart(i use django session and ajax)
you look at the code that I wrote and tell me why always the "cart not exist" is displayed
to solve the problem what I do?

class add_to_cart(View):
    def post(self,request):
        ref_id = request.POST.get('ref_id',None)
        if(ref_id):
            print("request.session={}".format(request.session))
            # flag = request.session.get('cart',None)
            if 'cart' not in request.session:
                print("cart not exist")
                request.session['cart'] = {ref_id:1}
            else:
                print("cart exist")
                if ref_id in request.session['cart']:
                    print("ref_id exist in cart")
                else:
                    print("ref_id not exist in cart")
        else:
            print("ref_id has not sent")  

In the meantime, I'm sure that I've written code Ajax is correct


Solution

  • I found the solution
    Should after every each change the session use:

    request.session.save()
    

    I thank everyone for their help