Не могу удалить товары из корзины. Please help. Exception Value: local variable 'product' referenced before assignment
views.py
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404
from django.urls import reverse
from .models import Cart, CartItem
from web.models import Product
def view(request):
try:
the_id = request.session['cart_id']
except:
the_id = None
if the_id:
cart = Cart.objects.get(id=the_id)
context = {'cart': cart}
else:
empty_message = "Ваша корзина пуста"
context = {"empty": True,
'empty_message': empty_message, }
return render(request, 'view.html', context)
def remove_from_cart(request, id):
cart = Cart(request)
product = get_object_or_404(Product, id=id)
cart.remove(product)
# the_id = request.session['cart_id']
# cart = Cart.objects.get(id=the_id)
#
# cartitem = CartItem.objects.get(id=id)
# cartitem.cart = None
# cartitem.save()
return HttpResponseRedirect(reverse("cart"))
def add_to_cart(request, slug):
request.session.set_expiry(100000)
try:
qty = request.GET.get('qty')
update_qty = True
except:
qty = None
update_qty = False
try:
the_id = request.session['cart_id']
except:
new_cart = Cart()
new_cart.save()
request.session['cart_id'] = new_cart.id
the_id = new_cart.id
cart = Cart.objects.get(id=the_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
cart_item, update= CartItem.objects.get_or_create(cart=cart, product=product)
if update_qty and qty:
if int(qty) == 0:
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
else:
pass
new_total = 0.00
for item in cart.cartitem_set.all():
line_total = float(item.product.price) * item.quantity
cart.line_total = line_total
new_total += line_total
request.session['items_total'] = cart.cartitem_set.count()
cart.total = new_total
cart.save()
return HttpResponseRedirect(reverse("cart"))