Django:如何在会话变量更改后自动刷新页面?

时间:2019-11-02 21:08:05

标签: html django session-variables nav django-sessions

我仅使用html渲染导航栏

在导航栏上,我通过来显示购物车中当前的商品数量 request.session.cart_items,其中cart_items是我的会话变量

当我向购物车中添加商品时,我的cart_items发生了变化,我发现使用print(request.session.cart_items)时确实发生了变化

问题在于,刷新页面时,我的html仅显示更新的request.session.cart_itemsrequest.session.cart_items更改后,如何使页面自动刷新?

这是我的navbar.html

<nav class="main-nav">
    <ul>  
      <li>
        <a href="/">Painting Website</a>
      </li>
      <li>
        <a href="/">{{ request.session.cart_items}}</a>
      </li>
    </ul>
</nav>

如果有帮助,这里也是我的CartUpdateAPIView(APIView)中的views.py

class CartUpdateAPIView(APIView):

    permission_classes  = [permissions.AllowAny]

    def get(self, request, pk=None, *args, **kwargs):

        product_id = request.get('product_id')

        product_obj = Painting.objects.get(pk=product_id)
        cart_obj, new_obj= Cart.objects.new_or_get(request)
        #remove from cart if already in cart
        if product_obj in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
        #add to cart if not in cart already
        else:
            cart_obj.products.add(product_obj) #adding to many-to-many

        return redirect("cart-api:cart-list")

    def post(self, request, pk=None, *args, **kwargs):

        product_id = request.data['products'][0]


        #to make sure that product_id is actually coming through
        if product_id is not None:

            try:
                #getting an instance of the painting from the Painting model
                product_obj = Painting.objects.get(id=product_id)
            except Painting.DoesNotExist:
                print("Sorry this product is out of stock.")

            cart_obj, new_obj = Cart.objects.new_or_get(request)

            #remove from cart if already in cart
            if product_obj in cart_obj.products.all():
                cart_obj.products.remove(product_obj)

            #add to cart if not in cart already
            else:
                cart_obj.products.add(product_obj) #adding to many-to-many

            #getting the total number of items in cart. need this to show the number of items in cart in the nav bar
            request.session['cart_items'] = cart_obj.products.count() 


        return redirect("cart-api:cart-list")

非常感谢!

0 个答案:

没有答案