You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板嵌套for循环无内容显示问题求助

解决Django分类新闻内层循环不显示的问题

问题根源及修复步骤

1. 模板变量与反向关联名称错误

外层循环遍历的变量是cat,但内层循环错误使用了未定义的category变量;同时,由于模型名为Article,Django默认的反向关联名称是article_set,而非模板中写的news_set。

修复后的模板循环代码:

{% for news in cat.article_set.all %}

如果想保留news_set作为关联名称,可以在Article模型的外键字段中添加related_name参数:

category = models.ForeignKey(
    Category, on_delete=models.SET_NULL, null=True, blank=True,
    default=None, related_name='news_set')

2. 条件过滤过于严苛

模板中仅显示forloop.counter == 4的条目,若分类下新闻数量不足4条,将不会渲染任何内容。根据需求调整条件:

  • 若要显示前3条:{% if forloop.counter <= 3 %}
  • 若要显示所有新闻:直接移除该if判断

3. 未过滤已发布状态的新闻

Article模型的is_published字段默认值为False,需只加载已发布的新闻,避免显示草稿内容:

{% for news in cat.article_set.filter(is_published=True) %}

4. 优化查询性能(可选)

为避免Django执行N+1次查询,在视图中使用prefetch_related预加载分类对应的新闻:

def home(request):   
    cats = Category.objects.all()[:4].prefetch_related('article_set')
    articles = Article.objects.filter(is_published=True)    
    return render(request, 'pages/home.html', context={
        'articles': articles,
        'cats': cats,
    })

完整修改后的模板片段

<div class="container-fluid">
<div class="container">
    <div class="row">
        {% for cat in cats %}
        <div class="col-lg-6 py-3">
            <div class="bg-light py-2 px-4 mb-3">
                <h3 class="m-0">{{cat.category_name}}</h3>
            </div>
            <div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative">
                {% for news in cat.article_set.filter(is_published=True) %}
                <!-- 这里调整条件,比如显示前3条 -->
                {% if forloop.counter <= 3 %}
                <div class="position-relative">
                    <img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;">
                    <div class="overlay position-relative bg-light">
                        <div class="mb-2" style="font-size: 13px;">
                            <a href="">{{news.title}}</a>
                            <span class="px-1">/</span>
                            <span>{{news.created_at}}</span>
                        </div>
                        <a class="h4 m-0" href="">{{news.description}}</a>
                    </div>
                </div>
                {% endif %}
                {% endfor %}
            </div>
        </div>
        {% endfor %}
    </div>
</div>

内容的提问来源于stack exchange,提问作者Carlos Eduardo Vieira Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:03:17