'TypeError: Object of type Cart is not JSON serializable
I just started using session in Django framework. I have create an object cart from Cart model. And when i wan to set cart inside request.session with session['cart'] = cart, I get this error message: TypeError: Object of type Cart is not JSON serializable
This is my Cart model
class Cart(object):
def __init__(self):
self.items = []
def addItem(self, itemCart):
try:
# get index of itemCart if exist
index = self.items.index(itemCart)
# itemCart exist then set its quantity
self.items[index].setQuantity(
self.items[index].quantity + itemCart.quantity)
except ValueError:
# the item does not exits then add to items list
self.items.append(itemCart)
This is my view when i update the session
cart = Cart()
session['cart'] = cart
And When i run the code i get this error: File "C:\Users\Patrick-PC\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type Cart is not JSON serializable.
Please help
Solution 1:[1]
If Cart
is a model, you'll want to inherit from models.Model
. That said, you can try:
from django.core import serializers
session['cart'] = serializers.serialize('json', Cart.objects.all())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | notanumber |