【发布时间】:2019-01-21 15:19:51
【问题描述】:
我从这篇文章中得到了提示 Customising tags in Django to filter posts in Post model
我已经创建了模板标签,但我不确定如何在我的 html 中使用它。我有一个 home.html,我想在其中显示三个精选帖子。我正在寻找类似 {% for post in features_post %} 的内容,然后显示帖子详细信息。
另外,我是否需要像上面的帖子一样创建一个 features_posts.html,因为我不希望为特色帖子添加任何额外的页面。除了其他内容之外,我只想让他们添加到我的主页上。
我想要做的是我在
下创建了一个模板标签from django import template
register = template.Library()
@register.inclusion_tag('featured_posts.html')
def featured_posts(count=3):
if Post.is_featured:
featured_posts = Post.published.order_by('-publish')[:count]
return {'featured_posts': featured_posts}
我在这里面临的问题是我无法从模型中导入 Post 模型。我的目录结构有点像这样:- 我有一个名为帖子的应用程序。 在里面我有 models.py 和 templatetags 模块,在模板标签里面我有 blog_tags.py
我无法进行相对导入。
然后创建了一个新页面 features_posts.html 如下:-
<ul>
{% for post in featured_posts %}
<li>{{ post.title }} </li>
{% endfor %}
</ul>
现在,我想在 home.html 中使用它。我该如何使用它?
编辑:- 如上所述,我可以按如下方式加载模型:-
from posts.models import Post
【问题讨论】:
-
这就是包含标签的实现方式。正如给定链接所描述的那样:函数、模板,然后在父/主模板中调用您的函数。 {% for %} 循环将在您的辅助模板中。
-
我是新手,我刚刚编辑了关于如何尝试的问题。你能指导我怎么做吗?
-
您在标签功能中的错误与链接中的OP相同。看看那里的答案。 `featured_posts.html` 很好。
-
哦,是的...我已经更正了。我在 home.html
{% load blog_tags %} {% for post in featured_posts %}{{ post.title }}{% endfor %}中执行此操作,但我的 home.html 中没有任何内容。正如我所提到的,其中一个可能的原因是我没有在标签中包含模型类。 (阅读上面我在做这件事时面临的问题)@IvanStarostin
标签: python django python-3.x django-templates django-template-filters