Using python 3.7
When I add item to the cart, the item gets added individually to each user, but I have delete button on the cart details page and the function in views.py looks like this:
def delete_cart_item(request, item_id):
user_profile = get_object_or_404(User_Profile, user=request.user)
shopping_cart = user_profile.shopping_cart_set.first()
item = shopping_cart.items.get(pk=item_id)
item.delete()
return redirect('Sales:cart_details')
Those are my models:
class User_Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Item(models.Model):
item_name = models.CharField(max_length=200)
item_price = models.IntegerField()
item_description = models.CharField(max_length=300)
item_bought_price = models.IntegerField()
stock_level = models.IntegerField()
restock_level = models.IntegerField()
class Cart_Item(models.Model):
item = models.OneToOneField(Item, on_delete=models.SET_NULL, null=True)
class Shopping_Cart(models.Model):
ref_code = models.CharField(max_length=15)
owner = models.ForeignKey(User_Profile, on_delete=models.SET_NULL, null=True)
items = models.ManyToManyField(Cart_Item)
What is the issue here? I tried changing on_delete=models.SET_NULL
of Cart_Item
to on_delete=models.CASCADE
but that didn't seem to change anything.
There also is a weird issue that when the cart is empty and I add the first item, that item cannot be deleted from the page, I can delete it from shell though.
You're deleting the actual item, rather than removing it from the many-to-many. You should do:
item = Item.objects.get(pk=item_id)
shopping_cart.items.remove(item)