A.z575
A.z575

Reputation: 59

How to implement function to delete all items from cart (django)

hey guys I made a website in django and it has a cart feature in it . Currently I've implemented a feature that you can delete items but it only deletes them on by one. I'm stuck on how to get the feature to delete all items currently in the cart

cart.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 %}

cart urls.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'),
]

cart views.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')

Upvotes: 0

Views: 739

Answers (1)

DanielM
DanielM

Reputation: 4043

Your view uses get which returns the one CartItem that fits product=product, cart=cart, if there are more than one - the get will throw an exception and fail.

But in order to delete all items in the cart, you can ignore the product 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')

Upvotes: 2

Related Questions