Chris
Chris

Reputation: 459

Creating a 'delete cart' button in django

I'm trying to create a button (on the user side) that deletes/cancels the user's cart.

Can I just do something like this?

views.py

def cancel_cart(request, id):

    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None

    cart.delete()
    messages.success(request, "You have cancelled your order.")
    return HttpResponseRedirect('profile.html')

Upvotes: 0

Views: 225

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34583

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.

Upvotes: 1

Related Questions