【问题标题】:For loop inside a IF condition to show right category on django templateFor 在 IF 条件内循环以在 django 模板上显示正确的类别
【发布时间】:2022-11-11 11:41:31
【问题描述】:

我正在尝试使用带有 for 循环的 if 条件在类别部分中显示正确的文章,到目前为止,我正在显示所有文章,而不是唯一应该在类别中的文章。

home.html

这是我的模板:

{% if articles.category == Sports %}
                {% for article in articles %}
                <div class="position-relative">
                    <img class="img-fluid w-100" src="{{article.cover.url}}" style="object-fit: cover;">
                    <div class="overlay position-relative bg-light">
                        <div class="mb-2" style="font-size: 13px;">
                            <a href="">{{article.title}}</a>
                            <span class="px-1">/</span>
                            <span>{{article.created_at}}</span>
                        </div>
                        <a class="h4 m-0" href="">{{article.description}}</a>
                    </div>
                </div>
                {% endfor %}
                {% endif %}

这里是我的views.py:

def home (request):   
cats = Category.objects.all()
articles = Article.objects.filter( is_published=True).order_by('-category')

return render (request,'pages/home.html',
context={
'cats': cats, 
'articles': articles
})

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以让用户使用以下内容搜索类别,而不是像这样对其进行硬编码:

    articles = Article.objects.filter(category__icontains=q).values('title')
    

    其中q 将是表单中的用户输入。

    【讨论】:

    • 是的,这是个好主意,但我想这样展示(我会在帖子上上传图片)
    • 那么我认为您只是缺少“体育”周围的引号,除非您有两个单独的文章和类别模型,否则您需要使用外键连接它们并使用__set stackoverflow.com/questions/42080864/…
    • 嗯,它仍然无法正常工作,它显示了所有文章,而不仅仅是“体育”
    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多