Skip to content Skip to sidebar Skip to footer

Adding A List Of Menu Items In A Django Session

I have the user menu in an object list, and I want to put it into the django sesion. I've trying but django tells me 'list' object has no attribute '_meta' actually this is the o

Solution 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 ... isnot JSON serializable

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

classMenuItem(object):
    def__init__(self, id, name, link, items=None):
        self.id = id
        self.name = name
        self.link = link
        self.items = items

    defserialize(self):
        return self.__dict__

Then,

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

Post a Comment for "Adding A List Of Menu Items In A Django Session"