Reputation: 79
in my django ecommerce I want to save session data for users not logged in. About saving cart ind DB, updating and retrieving it for logged users it's all ok, but how I can proceed for guest users? I tried in this way, but I think this is not a good solution: I save id cart in session and whole cart in database..Could you help me?
This is my views.py:
def update_cart(request, slug):
if request.user.is_authenticated:
#ok here...
else:
try:
the_id = request.session["cart_id"]
except:
new_cart = Cart()
product = Product.objects.get(slug=slug)
new_cart.save()
request.session["cart_id"] = new_cart.id
new_cart.products.add(product)
new_cart.save()
return HttpResponse("<h1>okkk!</h1>")
cart = Cart.objects.get(id = the_id)
product = Product.objects.get(slug=slug)
if not product in cart.products.all():
cart.products.add(product)
cart.save()
return HttpResponseRedirect(reverse("cart"))
else:
cart.products.remove(product)
return HttpResponseRedirect(reverse("cart"))
and they are my Cart model and Product model:
class Cart(models.Model):
user = models.OneToOneField(User, on_delete="CASCADE", null=True)
products = models.ManyToManyField(Product, blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
image = models.FileField(upload_to="products/images", blank=True, null=True)
quantity = models.IntegerField(default=1)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
class Meta:
unique_together = ('title', 'slug')
def __str__(self):
return self.title
Upvotes: 1
Views: 6872
Reputation: 542
Use a dictionary to populate all the necessary information of a product like this
product_document = {
'title': product.title,
'price': product.price
}
And you can use this to store in the session with the key 'cart' which is an empty dictionary at the beginning and perform adding, updating and deleting of product_document as you would do with any dictionary element.
For example adding a product to the cart would be:
request.session['cart'] = {}
request.session['cart'][str(product.id)] = product_document
Upvotes: 2