我從這篇文章中獲得了一些提示,即 在Django中自定義標(biāo)簽以過濾Post模型中的帖子我已經(jīng)創(chuàng)建了模板標(biāo)簽,但不確定如何在html中使用它。我有一個(gè)home.html,我想在其中顯示三個(gè)特色文章。我正在尋找類似{%for features_post%}中的帖子,然后顯示帖子的詳細(xì)信息。另外,我是否一定需要像上面的帖子中那樣創(chuàng)建featured_posts.html,因?yàn)槲也幌霝樵撎犹砑尤魏晤~外的頁面。我只希望他們在其他內(nèi)容上添加我的主頁。我想做的是我已經(jīng)創(chuàng)建了一個(gè)模板標(biāo)簽,如下from django import templateregister = 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}我在這里面臨的問題是我無法從模型中導(dǎo)入Post模型。我的目錄結(jié)構(gòu)有點(diǎn)像這樣:-我有一個(gè)名為posts的應(yīng)用程序。在其中,我具有models.py和templatetags模塊,在模板標(biāo)簽中,我具有blog_tags.py我無法進(jìn)行相對導(dǎo)入。然后創(chuàng)建新頁面featured_posts.html,如下所示:-<ul> {% for post in featured_posts %} <li>{{ post.title }} </li> {% endfor %}</ul>現(xiàn)在,我想在home.html中使用它。我該如何使用?編輯:-如上所述,我可以按以下方式加載模型:-from posts.models import Post
1 回答

隔江千里
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
home.html
{% load blog_tags %} {% featured_posts %}
呼叫您的標(biāo)簽。就是這樣。
或者
{% featured_posts count=15 %}
請注意,featured_posts
這里不是for
上下文的發(fā)布列表(在循環(huán)中迭代),而是函數(shù)名稱:def featured_posts(count=3)
。它們在您的代碼中具有相同的名稱,這可能使您有些困惑。
添加回答
舉報(bào)
0/150
提交
取消