Iván Casanova Iván Casanova - 2 months ago 18
Python Question

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 object that represents a item in the menu

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


and in a function I append MenuItems in a list.

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


finally in the view I try to put the menu in session.

request.session['menu'] = menu


And in this part is when django throws a


'list' object has no attribute '_meta' error.

Answer

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
Comments