Dhiman
Dhiman

Reputation: 113

Remove products from cart in django

I wrote a code to remove products from cart but instead it adds products to the cart.
Here's my views.py

def delete_cart(request, slug):
    products = get_object_or_404(Products, slug=slug)
    cart = Cart.objects.get(user = request.user, products=products)
    cart.delete()
    return redirect('cart')

urls.py

path('delete/cart/item/<slug:slug>/', views.delete_cart, name = 'delete-cart')

What is wrong with this codes?
Any suggestion will be reallly helpful.

Upvotes: 1

Views: 323

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

Based on your comment, this was a clash between two paths: two paths that have certain possible paths in common. In that case, Django will pick the first one of the matching paths, hence the delete_cart view is never called.

You can further simplify the view logic to:

def delete_cart(request, slug):
    Cart.objects.filter(user=request.user, products__slug=products).delete()
    return redirect('cart')

furthermore since this is a view that alters entities, this should be done through a POST or DELETE request, not a GET request, so you might want to restrict the view with the @require_http_methods(…) decorator [Django-doc]:

from django.views.decorators.http import require_http_methods

require_http_methods(['POST', 'DELETE'])
def delete_cart(request, slug):
    Cart.objects.filter(user=request.user, products__slug=products).delete()
    return redirect('cart')

In that case you thus create a mini form that will make the POST request with:

<form method="POST" action="{% url 'delete-cart' product.slug %}">
    {% csrf_token %}
    <button type="submit">remove from the cart</button>
</form>

with delete-cart the name of the path that refers to the delete_cart view.

Upvotes: 2

Related Questions