I'm pretty new to Django and face a problem trying to implement a cart for my e-shopping website. As I call my "add_to_cart" function, I want to be sure if either a cart exists for this session, and if there is already a reference for the selected item in this cart.
Here is my models.py :
CART_ID = 'CART-ID'
class Cart(models.Model):
creation_datetime = models.DateTimeField(auto_now_add=True)
update_datetime = models.DateTimeField(auto_now=True)
checked_out = models.BooleanField(default=False)
user = models.ForeignKey(User,on_delete=models.DO_NOTHING, null=True, blank=True)
@classmethod
def create(cls):
cart_id = request.session.get(CART_ID)
if cart_id:
cart = models.Cart.objects.filter(id=cart_id, checked_out=False).first()
if cart is None:
cart = cls()
request.session[CART_ID] = cart.id
else:
cart = cls()
request.session[CART_ID] = cart.id
return cart
def add(self, article, prix_unitaire, quantite=1):
item = Item.objects.filter(cart_id=self.id, article=article).first()
if item:
item.prix_unitaire = prix_unitaire
item.quantite += int(quantite)
item.save()
else:
Item.objects.create(cart_id=self.id, article=article, prix_unitaire=prix_unitaire, quantite=quantite)
class Item(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
quantite = models.PositiveIntegerField()
prix_unitaire = models.PositiveIntegerField()
def prix_total(self):
return self.quantite * self.prix_unitaire
prix_total = property(prix_total)
in my views.py, I defined my "add_to_cart" function :
def add_to_cart(request, pk, quantite=1):
article = Article.objects.get(pk=pk)
cart = Cart(request)
cart.add(article, article.prix_unitaire, quantite)
and my urls.py
urlpatterns = [
...
path('add_to_cart/<int:pk>/', add_to_cart, name='add_to_cart'),
As I call the function, I get this error :
TypeError at /marketplace/add_to_cart/5/
Field 'id' expected a number but got <WSGIRequest: GET '/marketplace/add_to_cart/5/'>.
In the stack, I have this highlighted :
/home/max/elien_dev/ELIEN_MARKETPLACE/models.py, line 85, in add
item = Item.objects.filter(cart_id=self.id, article=article).first() …
▼ Local vars
Variable Value
article <Article: Article object (5)>
prix_unitaire 400
quantite 1
self <Cart: Cart object (<WSGIRequest: GET '/marketplace/add_to_cart/5/'>)>
It seems that I'm not referencing my cart as I should as I try to check if the item is already in the cart. Tried with "cart=self" and other stuff, but I think I'm missing a deeper point here. Any idea ?
Thanks anyway for reading this !