adding a list of menu items in a django session
<p>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 </p>

<pre><code>'list' object has no attribute '_meta'
</code></pre>

<p>actually this is the object that represents a item in the menu</p>

<pre><code>class MenuItem(object):
    def __init__(self, id, name, link, items=None):
        self.id = id
        self.name = name
        self.link = link
        self.items = items
</code></pre>

<p>and in a function I append MenuItems in a list.</p>

<pre><code>menu = []
menu.append(MenuItem(1,
                     "hi",
                     "some_link"))
</code></pre>

<p>finally in the view I try to put the menu in session. </p>

<pre><code>request.session['menu'] = menu
</code></pre>

<p>And in this part is when django throws a </p>

<blockquote>
  <p>'list' object has no attribute '_meta' error.</p>
</blockquote>

<p>This is happening because the object you're trying to store in the session is not serializable.</p>

<p>You can test with with</p>

<pre><code>import json
json.dumps(MenuItem(1, "hi", "some_link"))
</code></pre>

<p>Which gives</p>

<pre><code>MenuItem object at ... is not JSON serializable
</code></pre>

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

<pre><code>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__
</code></pre>

<p>Then,</p>

<pre><code>menu = []
menu.append(MenuItem(1, "hi", "some_link").serialize())
request.session["menu"] = menu
</code></pre>

python django session menu