1

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

1
  • The Cart object 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 .dump and .load methods for your Cart class, and use these methods to exchange the object shape between the states. Commented Jul 27, 2019 at 21:26

1 Answer 1

2

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())
Sign up to request clarification or add additional context in comments.

3 Comments

The Cart is not a django model as shown above. You can't do .objects on it.
Which is why I prefaced my answer with "if Cart is a model". It wasn't clear to me if it was a transcription error or they had mistakenly forgot to derive from models.Model.
A Cart instance would need to contain a arbitrary number of Item objects, which would involve two more steps of interaction levels between the two, and these would have to be implemented to be used towards the end with the approach you suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.