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
Cartobject would need to be serialized correctly (JSON or pickle if specified in settings.py) to make it possible to be stored in a session. A session cannot take a python instance, it would need serialization/deserialization steps in between. Consider adding.dumpand.loadmethods for yourCartclass, and use these methods to exchange the object shape between the states.