[Answer]-Creating a 'delete cart' button in django

1👍

I think you probably want to go with something like:

from django.core.urlresolvers import reverse

def cancel_cart(request):
    cart_id = request.session.get('cart_id')
    if cart_id:
        try: # code defensively, even against yourself
            cart = Cart.objects.get(id=cart_id)
            cart.delete()
            messages.success(request, "You have cancelled your order.")
        except Cart.DoesNotExist:
            pass
    return HttpResponseRedirect(reverse('your_app:some_url_name'))

This way, the delete is only attempted if the cart_id key is present in the session, since .get() returns None by default. You can further prevent errors by adding try/except handling when retrieving the cart instance in case you have a non-existent id in session.

Not sure why you would need to pass in the id to retrieve, since you’re getting it from the session. You could set that as an optional parameter to delete a specific cart object if it’s not in session I guess.

Leave a comment