在 Django 会话中添加菜单项列表 [英] adding a list of menu items in a django session
问题描述
我在对象列表中有用户菜单,我想把它放到 django 会话中.我试过了,但 Django 告诉我
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
在一个函数中,我将 MenuItems 附加到列表中.
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
这部分是 django 抛出一个
And in this part is when django throws a
'list' 对象没有属性 '_meta' 错误.
'list' object has no attribute '_meta' error.
推荐答案
发生这种情况是因为您尝试在会话中存储的对象不可序列化.
This is happening because the object you're trying to store in the session is not serializable.
你可以用
import json
json.dumps(MenuItem(1, "hi", "some_link"))
哪个给了
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__
那么,
menu = []
menu.append(MenuItem(1, "hi", "some_link").serialize())
request.session["menu"] = menu
这篇关于在 Django 会话中添加菜单项列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!