如何访问 Django 模板中不相关的模型?
我想使用一个应用程序来创建一个易于使用管理界面进行编辑的菜单。像这样:
class Menu_item
name = models.CharField()
item_url = models.URLField()
我的模板看起来像这样:
{% 扩展 base.html %}
div ID="nav"
{{ foo.navbar.? }}
/div
div ID="内容"
{% 块内容 %}{% endblock %}
/div
我希望 div#nav 包含基于上述模型的 ul,但只是不知道如何实现这一点。看起来 object_list 通用视图会很棒,但是 URL 访问填充 div#content 的模型的视图。有人有什么建议吗?有没有一种方法可以在没有 URL 的情况下访问通用视图?
谢谢。
I want to use an app to create a menu that is easy to edit with the admin interface. Something like this:
class Menu_item
name = models.CharField()
item_url = models.URLField()
My template looks something like this:
{% extends base.html %}
div ID="nav"
{{ foo.navbar.? }}
/div
div ID="Content"
{% block content %}{% endblock %}
/div
I want div#nav to contain a ul based upon the above model but just can't figure out how to accomplish this. It seems like an object_list generic view would be great but, the URL accesses the view for the model that populates div#content. Does anyone have any suggestions? Is there a way to access a generic view without a URL?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,在您看来,从 db 获取数据:
在模板中:
First, in you view, get data from db:
And in template:
我发现了一个解决方案。包含标签。
我所做的是创建一个包含标签,它相当于一个简单的自定义模板标签(django 为您提供了一个快捷方式!)。
这是我所做的:
这允许我在管理界面中为每一层导航(主要、次要等)创建一个 Menu_choice 对象
(注意导航栏而不是导航栏)
<前><代码>
{% 导航栏中的菜单项 %}- {{ menu_item.name }}</a></li>
{% 结束 %}
我想要主导航的位置:
注意:发送到包含标签的字符串周围的引号很重要。在我弄清楚这一点之前,我花了相当长的时间试图让它发挥作用。
同时非常感谢 dikamilo 的帮助。
I have discovered a solution. Inclusion Tags.
What I did was create an inclusion tag, which amounts to a simple custom template tag (django provides a shortcut for you!).
Here is what I did:
This allows me to create a Menu_choice object in the admin interface for each layer of navigation (primary, secondary, etc)
(Note navBar as opposed to navbar)
And where I want primary navigation:
Note: the quotes around the string you are sending to your inclusion tag are important. I spent a ridiculously lengthy bit of time trying to make it work before I figured that out.
Also a big thank you to dikamilo for the help.