我正在尝试创建一个删除/取消用户购物车的按钮(在用户端)。
我可以这样做吗?
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')
答案 0 :(得分: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.