我从这篇文章中得到了一个提示,Customising tags in Django to filter posts in Post model
我已经创建了模板标签,但是我不确定如何在我的html中使用它。我有一个home.html,我想在那里显示三个特色帖子。我正在寻找类似{% for post in featured_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}我在这里面临的问题是我不能从model导入Post模型。我的目录结构有点像这样:-我有一个名为post的应用程序。在它里面有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发布于 2018-08-15 03:27:30
home.html
{% load blog_tags %}
{% featured_posts %}给你的标签打电话。就这样。
或
{% featured_posts count=15 %}注意,这里的featured_posts不是来自上下文的post列表(在for循环中迭代),而是函数名:def featured_posts(count=3)。它们在您的代码中具有相同的名称,这可能会让您有点困惑。
https://stackoverflow.com/questions/51846977
复制相似问题