[Fixed]-Adding a list of menu items in a django session

1👍

This is happening because the object you’re trying to store in the session is not serializable.

You can test with with

import json
json.dumps(MenuItem(1, "hi", "some_link"))

Which gives

MenuItem object at ... is not JSON serializable

One thing you can do is write your own function to serialize the object. Here’s one way to approach it:

class MenuItem(object):
    def __init__(self, id, name, link, items=None):
        self.id = id
        self.name = name
        self.link = link
        self.items = items

    def serialize(self):
        return self.__dict__

Then,

menu = []
menu.append(MenuItem(1, "hi", "some_link").serialize())
request.session["menu"] = menu
👤NS0

Leave a comment