我想使用TEMPLATE_CONTEXT_PROCESSORS创建一个动态菜单,其中包含存储在数据库中的值的子菜单
我的模型“菜单”有这个:
-short_name
-description
-url
-father(ForeignKey(self,null=True))
我的参赛作品可能是这样的:
PK| SHORT DESC |DESCRIPTION |URL |MENU_PK(father)
1 | Home |Fist Page |home |null
2 | Administration|Site SetUp |admin |null
3 | Users |Users Admin |users |2
4 | Warehouses |Warehouses Admin|warehouses|2
...
我想创建一个这样的字典:
{'menu':[
{'name':'Home','url':reverse('home')},
{'name':'Administration','url':reverse('admin'),'menu':[
{'name':'Users','url':reverse('users')},
{'name':'Warehouses','url':reverse('warehouses')},
]},
{'name':'Products','url':reverse('products'),'menu':[
{'name':'New Product','url':reverse('newProduct')},
{'name':'Report','url':reverse('productReport')},
]},
{'name':'Blog','url':reverse('blog')},
...
]}
然后我可以在模板中制作动态菜单, 你知道怎么做吗?
我试图像这样制作字典:
menudb = Menu.objects.filter(perfil__usuario__username=request.user.username)
if menudb.count()>0:
menus = {menu:[]}
for m in menudb:
data = {}
data["name"]=m.name
data["url"]=reverse(m.url)
if m.father is not None:
subs = {menu:[]}
for sub in m.father:
subm = {}
subm["name"] = sub.name
subm["url"] = reverse(sub.url)
subs["menu"].append(subm)
data["menu"]=sub
menus["menu"].append(data)