我从这篇文章中获得了一些提示,即 在Django中自定义标签以过滤Post模型中的帖子
我已经创建了模板标签,但不确定如何在html中使用它。我有一个home.html,我想在其中显示三个特色文章。我正在寻找类似{%for features_post%}中的帖子,然后显示帖子的详细信息。
另外,我是否一定需要像上面的帖子中那样创建featured_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模型。我的目录结构有点像这样:-我有一个名为posts的应用程序。在其中,我具有models.py和templatetags模块,在模板标签中,我具有blog_tags.py
我无法进行相对导入。
然后创建新页面featured_posts.html,如下所示:-
<ul>
{% for post in featured_posts %}
<li>{{ post.title }} </li>
{% endfor %}
</ul>
现在,我想在home.html中使用它。我该如何使用?
编辑:-如上所述,我可以按以下方式加载模型:-
from posts.models import Post
隔江千里
相关分类