Django,页面在ID删除后正在渲染对象

时间:2019-04-06 20:49:34

标签: python django model

我在会话中存储了对象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)```

1 个答案:

答案 0 :(得分:0)

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

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

请参见the Django docs on sessions