Search code examples
jsondjangoserializable

Object of type 'Mycart' is not JSON serializable in Django


I want to add dictionary(having models) datatype object to request.session but getting "Object of type 'Mycart' is not JSON serializable in Django"

product_details = {}
for product in products_in_cart:
    product_details.update({product.id: 
    (product,request.POST['quantity'+str(product.product.id)])})  
request.session['product_details'] = product_details

I expect the dictionary updated in session but the actual output is "Object of type 'Mycart' is not JSON serializable in Django"


Solution

  • The problem is with the product which is the first parameter of your tuple inside of your dictionary. you need to serialize it before you can use it in your tuple like this:

     from django.core import serializers
    
     product_details = {}
     for product in products_in_cart:
         s_product = serializers.serialize("json", [product])
         product_details.update({product.id: 
        (s_product,request.POST['quantity'+str(product.id)])})  
         request.session['product_details'] = product_details