嘿伙計們,我在 django 中創建了一個網站,其中有一個購物車功能。目前我已經實作了一項功能,您可以洗掉專案,但它只能逐個洗掉。我被困在如何獲得洗掉當前在購物車中的所有專案的功能上
購物車.html
{% for cart_item in cart_item %}
{% if cart_item.quantity < cart_item.product.stock %}
<a <a href="{% url 'cart:full_remove' cart_item.product.id %}" class="custom_icon"><i class="fas fa-trash-alt custom_icon"></i></a>
{% endif %}
{% endfor %}
購物車網址.py
from os import name
from django.urls import path
from . import views
app_name='cart'
urlpatterns = [
path('add/<uuid:product_id>/', views.add_cart, name='add_cart'),
path('', views.cart_detail, name='cart_detail'),
path('remove/<uuid:product_id>/', views.cart_remove, name='cart_remove'),
path('full_remove/<uuid:product_id>/', views.full_remove, name='full_remove'),
]
購物車視圖.py
def full_remove(request, product_id):
cart = Cart.objects.get(cart_id=_cart_id(request))
product = get_object_or_404(Product, id=product_id)
cart_item = CartItem.objects.get(product=product, cart=cart)
cart_item.delete()
return redirect('cart:cart_detail')
uj5u.com熱心網友回復:
您的視圖使用 get 回傳CartItem適合的那個product=product, cart=cart,如果有多個 - get 將拋出例外并失敗。
但是為了洗掉購物車中的所有專案,您可以忽略產品 ID:
def full_remove(request): # Update urls.py so product_id is not needed.
cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=cart) # Filter all items in cart
cart_items.delete()
return redirect('cart:cart_detail')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/389562.html
上一篇:在推送到NavigationController和ViewDidLoad時進行除錯時獲取不同的物件
下一篇:基于函式args對資料幀執行操作
