从Django购物车中删除唯一商品

时间:2020-03-26 00:11:41

标签: python django

我正在尝试从cart中删除一个项目,但这样做有一些问题。这是函数:

def cart_contents(request):
    """
    Ensures that the cart contents are available when rendering
    every page
    """
    cart = request.session.get('cart', {})
    cart_items = []
    total = 0
    destination_count = 0
    for id, quantity in cart.items():
        destination = get_object_or_404(Destinations, pk=id)
        #remove = request.session.pop('cart', {id}) <<<<<<
        price = destination.price
        total += quantity * destination.price
        destination_count += quantity
        cart_items.append({'id': id, 'quantity': quantity, 'destination': destination, 'price':price, 'remove':remove})
    #cart_item will loop into the cart.
    return {'cart_items': cart_items, 'total': total, 'destination_count': destination_count}

Template.html

{% for item in cart_items %}

{{ item.remove }}

{% endfor %}

我添加了一个删除变量remove = request.session.pop('cart', {id}),但是如果我在代码中使用它,则它首先将不允许我添加多个项目,并且当我单击垃圾箱按钮以删除该项目时,删除会话中的所有cart。 下图根据其ID和数量{'id', quantity} = {'2': 1, '3': 2}在卡中包含两项。

shopping cart

2 个答案:

答案 0 :(得分:2)

request.session.pop('cart')将删除会话中的购物车。假设单击删除图标时,您传递了购物车商品的ID,则可以从会话中获取购物车并删除必要的ID,然后使用新的购物车值再次设置会话:

cart = request.session.get("cart", {})
id_to_be_removed = request.POST["id_to_be_removed"]

# do other things here or anywhere else

if id_to_be_removed in cart:
   del cart[id_to_be_removed]  # remove the id
   request.session["cart"] = cart

# return

答案 1 :(得分:0)

我找到了答案。我使cartquantity相互关联。因此,如果购物车中有3个项目,则可以删除/减少直到它在购物车中达到0,如果是,则购物车将重定向到目标网址。

def adjust_cart(request, id):
    """
    Adjust the quantity of the specified product to the specified
    amount

    url for this function should be <str:id> not <int:id>
    - otherwise you need to add str() method for each dict representation.
    """
    cart = request.session.get('cart', {})
    quantity = cart[id] - 1 #decreases the cart quantity until deletes from cart

    if quantity > 0:
        cart[id] = quantity
    else:
        cart.pop(id)
    request.session['cart'] = cart
    if not cart: #if all products be deleted from cart return to destination page
        return redirect(reverse('destination'))
    return redirect(reverse('view_cart'))

cart.html

{% for item in cart_items %}
</tr>
...
  <td class="border-0 align-middle"><a href="{% url 'adjust_cart' item.id%}" class="text-dark"><i class="fa fa-trash"></i></a></td>
</tr>
 {% endfor %}

url.py

from django.urls import path
from . import views

urlpatterns = [
    ...
    ...
    path('adjust/<str:id>/', views.adjust_cart, name="adjust_cart"),
]

请记住,cart_items是带有附加字典的列表。如果首字母缩写词有误,请您纠正我。