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

如何在Django模板循环中通过API展示不同数据

解决Django模板循环中所有卡片显示相同API数据的问题

你的核心问题在于视图函数没有正确传递API返回的数据列表,且模板循环逻辑未关联到数据项索引。以下是具体修正方案:

步骤1:修正视图函数

将API返回的有效数据列表直接传给模板,移除不必要的手动迭代器:

import requests
from django.http import HttpResponseServerError

def home_view(request):
    url = "https://random-recipes.p.rapidapi.com/ai-quotes/50"

    headers = {
        "X-RapidAPI-Key": "你的API密钥",  # 替换为实际密钥
        "X-RapidAPI-Host": "random-recipes.p.rapidapi.com"
    }

    # 处理API请求异常,避免页面崩溃
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        recipes = response.json()
    except requests.exceptions.RequestException as e:
        print(e)  # 可写入日志系统
        return HttpResponseServerError("获取数据失败")

    # 仅传递前11条数据,对应原需求的循环次数
    context = {'recipes': recipes[:11]}

    return render(request,'home.html', context=context)

说明:

  • 确保已安装requests库:执行pip install requests
  • 用recipes[:11]截取数据,替代手动创建的range(0,11),直接关联数据项
  • 添加异常处理,避免API请求失败导致页面报错

步骤2:修正模板代码

直接遍历数据列表,每个循环项对应一条独立的API数据:

<div class="container" id="card" >
    {% for recipe in recipes %}
    <div class="card1">
        <div class="card-header1">
            <img src="{{ recipe.image }}" alt="食谱图片" />
        </div>
        <div class="card-body1">
            <h4>
                <a href="/article/" style="text-decoration: none; color: inherit;" >{{ recipe.title }}</a>
            </h4>
            <p>
                {{ recipe.description|default:"An exploration into the truck's polarising design" }}
            </p>
            <div class="user1">
                <div class="user-info1">
                    <strong>By</strong>
                    <a href="">{{ recipe.author|default:"Rachel Lucas" }}</a>
                </div>
            </div>
        </div>
    </div>
    {% empty %}
    <p>暂无数据</p>
    {% endfor %}
</div>

说明:

  • 遍历recipes列表时,每个recipe对应API返回的单条数据,自动实现卡片内容差异化
  • 用|default过滤器处理API未返回的字段,保留原静态文本作为 fallback
  • 添加{% empty %}块,处理无数据时的提示逻辑

额外注意事项

如果API返回的是包含列表的字典(如{"data": [...], "count": 50}),需调整视图中获取数据的代码:

# 假设API返回结构为{"data": [...]}
recipes = response.json()['data']

内容的提问来源于stack exchange,提问作者Shamshad z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:27:29