首页 > 解决方案 > Django,页面在 id 被删除后呈现对象

问题描述

我在会话中存储和对象 id,并且我正在获取 id 来查询和呈现该模型的值,从会话中删除 id 后,该模型的值在页面重新加载后仍显示在模板中,我该如何停止呢?这是我的代码

def dashboard(request):
    customer_form = CustomerInfoForm()
    form = TransactionForm(initial={'tax':0,'price':0, 'price_per_item':0})

    if 'id' in request.session:
        id =  request.session['id']
        print('Id in dashboard is ', id)
        order = Order.objects.get(pk=id).item_set.all()
        sum_of_price = order.aggregate(Sum('price'))
        #Get sum of all item prices.
        if sum_of_price :
            context['price'] = sum_of_price['price__sum']
            context['current_order'] = Order.objects.get(pk=id).item_set.all()
    context['form'] = form
    context['customer_form'] = customer_form
    return render(request, 'main/dashboard.html', context)```

In the second view i am deleting the id and when i reload the page the first view still query and render values to the page, 

```@csrf_exempt
def add_order_as_credit(request):
    try:
        price = request.POST.get('price')
        id = request.session.get('id')
        order = Order.objects.get(pk=id)
        order.price = price
        order.save()
        print('Id is  ', request.session['id'])
        print('Price is ' + price)
        del request.session['id']
        return JsonResponse('Order has been set as credit', safe=False)
    except (KeyError, Order.DoesNotExist):
        return JsonResponse('There is no order ', safe=False)```

标签: pythondjangomodel

解决方案


在某些情况下,需要将会话显式标记为已修改:

del request.session['id']
request.session.modified = True

请参阅有关会话的 Django 文档


推荐阅读