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

Django渲染HTML数据异常:无法加载items数据至页面求助

Django模板无法加载数据的解决方案

核心问题

视图文件中传递给模板的上下文变量名大小写不匹配:

  • 在views.py中,你将查询结果传递为{"Item": items}(键为大写的Item)
  • 但在模板中,你尝试遍历的是小写的items变量,Django模板对变量名大小写严格敏感,导致无法匹配到数据。

修复步骤

修改views.py中的上下文字典,将键改为items:

from django.shortcuts import render
from .models import Product

def collections(request):
    items = Product.objects.all()
    return render(request, "shop/collections.html", {"items": items})

额外检查项

如果修复后仍无数据,请确认以下几点:

  • Product模型中确实定义了name字段
  • 数据库中已有Product类型的记录(可通过Django admin或shell查询确认)
  • 你的app已添加到settings.py的INSTALLED_APPS列表中
  • 已执行python manage.py makemigrations和python manage.py migrate命令完成模型迁移

内容的提问来源于stack exchange,提问作者20PCS812 PURSOTH V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:27:25