I have two apps in my project one is call store and the other is call cart in store I have all the models and in cart I have all the cart functionality. The call is handle using session when admin delete a product the cart icon count is like if the product has not been deleted from the session however the summary html show up the rights products in the cart (it doesn't include the deleted one but the cart icon show up a quantity that is wrong). how can I update the icon with the right quantity once admin delete the product, the cart need to be refresh and I have used a post_delete signal for this but it seems not to be working.
this is my code
cart/signals.py
from django.db.models.signals import post_delete
from django.dispatch import receiver
from store.models import Product
from django.contrib.sessions.models import Session
@receiver(post_delete, sender=Product)
def update_cart_on_product_delete(sender, instance, **kwargs):
# Get all sessions
sessions = Session.objects.all()
for session in sessions:
cart = session.get_decoded().get('cart', {})
if cart:
# Check if the deleted product is in the cart
if str(instance.id) in cart:
del cart[str(instance.id)]
# Save the updated cart back to the session
session.get_decoded()['cart'] = cart
session.save()
I have two apps in my project one is call store and the other is call cart in store I have all the models and in cart I have all the cart functionality. The call is handle using session when admin delete a product the cart icon count is like if the product has not been deleted from the session however the summary html show up the rights products in the cart (it doesn't include the deleted one but the cart icon show up a quantity that is wrong). how can I update the icon with the right quantity once admin delete the product, the cart need to be refresh and I have used a post_delete signal for this but it seems not to be working.
this is my code
cart/signals.py
from django.db.models.signals import post_delete
from django.dispatch import receiver
from store.models import Product
from django.contrib.sessions.models import Session
@receiver(post_delete, sender=Product)
def update_cart_on_product_delete(sender, instance, **kwargs):
# Get all sessions
sessions = Session.objects.all()
for session in sessions:
cart = session.get_decoded().get('cart', {})
if cart:
# Check if the deleted product is in the cart
if str(instance.id) in cart:
del cart[str(instance.id)]
# Save the updated cart back to the session
session.get_decoded()['cart'] = cart
session.save()
Share
Improve this question
asked Nov 19, 2024 at 21:20
Jose PerezJose Perez
91 bronze badge
1 Answer
Reset to default 0In standard Django templates, there is no dynamic re-rendering when a model changes. You can use WebSockets for this functionality. Take a look at this example with Channels