How to add products to cart using sessions as a guest in django
settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
models.py
class Product(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(default='-')
description = models.TextField()
unit_price = models.FloatField()
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection, on_delete=models.PROTECT)
promotions = models.ManyToManyField(Promotion)
class Cart(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
I want to add the products in the cart using session through cache. how can I make a key named as 'cart' in request.session and add those product's id in it. I initially tried to set 'cart' key using request.session.setdefault('cart', list()) but then I read the django documentation and it says that the items should be in the form of dictionaries(according to conventions). So what can I do to store the products in the cart for guest users?