添加到会话字典

时间:2017-01-02 16:30:48

标签: python django

我尝试创建一个视图功能,在添加和删除时更新用户购物车(会话)。

def shoppingCartAdd(request):
    data = json.loads(request.POST['post_data'])

    if 'shopping_cart' not in request.session: #<-- create the session dict
        request.session['shopping_cart'] = {}

    if data["action"] == "add":
        with open(MEDIA_ROOT + '/json/products.js', 'r') as json_file:
                products = json.loads(json_file.read()) #<-- json file that contains product information
        json_file.close()
        item = products["products"][data["id"]] #<-- get the item info from json

        #If the item is not in the session add it. Otherwise do something.        
        if data["id"] not in request.session['shopping_cart']: 
            request.session['shopping_cart'][data["id"]] = item
        else:
            print('Exists')
            #Do something else. 

    #Remove the item from the dict.
    if data["action"] == "remove":
        request.session['shopping_cart'].pop([data["id"]], None)


    context = {'shoppingCart' : request.session['shopping_cart']}    

    return JsonResponse(context)

我的问题是我不能在我的dictinary中添加两个以上的项目。我不确定我在这里做错了什么。如果我点击第一个项目,它将创建会话并正确添加,如果我尝试再次添加它,它将打印出#34;存在&#34;。但是,如果我添加一秒并尝试再次添加它,它将无法打印出来&#34;存在&#34;在第二项。

这是我用两个项目打印的会话。使用print(request.session['shopping_cart'])

{
'38': {'name': 'hergh', 'price': 23, 'active': 'active', 'pk': 38, 'imageURL': '/media/gg_faUCQOg.jpg', 'type': 'sokker', 'amount': 13}, 
'39': {'name': 'dea', 'price': 1, 'active': 'active', 'pk': 39, 'imageURL': '/media/gg_6ECtbKE.jpg', 'type': 'sokker', 'amount': 1}
}

1 个答案:

答案 0 :(得分:0)

根据文件 - https://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved

  

默认情况下,Django仅在会话被修改时保存到会话数据库 - 如果已分配或删除任何字典值,则

您可以将SESSION_SAVE_EVERY_REQUEST设置为True,这将强制在每个请求中保存会话。