Django模板无法读取数据库数据问题求助
Django模板无法读取数据库数据问题
在学习Django过程中遇到问题:尝试在模板中展示数据库数据时,模板无法读取到这些数据。已尝试删除数据库及迁移文件,重新创建数据库并添加新对象,但问题仍未解决。
相关代码
models.py代码
from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Product(models.Model): name= models.CharField( max_length= 100, verbose_name= 'Name' ) description= models.TextField(max_length= 500) photo= models.ImageField(upload_to= 'photos/%Y/%m/%d') price= models.FloatField(validators= [MinValueValidator(2.0), MaxValueValidator(1000000.0)],) amount= models.IntegerField() last_updated= models.DateTimeField(auto_now= True) is_published=models.BooleanField(default=False) category= models.ForeignKey( "Category", verbose_name= 'Category', default='Unselected', on_delete=models.SET_DEFAULT ) class Meta: verbose_name = "Product" verbose_name_plural = "Products" def __str__(self): return self.name class Category(models.Model): name=models.CharField(max_length=100) class Meta: verbose_name = 'Category' verbose_name_plural = "Categories" def __str__(self): return self.name
views.py代码
from django.shortcuts import render from .models import * # Create your views here. def index(request): print(request) product=Product.objects.all() return render(request,'main.html',{product :'product'})
模板文件(main.html部分代码)
{% for item in product %} <h1>{{item.name}}</h1> {% if item.photo %} <img src="{{item.photo.url}}" alt="Not found"> {% endif %} <p>{{item.description}}</p> <h2>{{item.price}}</h2> {% endfor %}
问题原因及解决方法
核心问题出在视图函数的上下文参数传递错误:
你在render函数中传入的上下文字典把键值对写反了,正确格式应为{'模板变量名': 数据对象},而非{数据对象: '模板变量名'}。
修改views.py中的代码:
def index(request): print(request) product = Product.objects.all() # 修正上下文字典的键值顺序 return render(request, 'main.html', {'product': product})
额外验证要点:
- 确认数据库中已创建有效的Product对象(可通过Django admin或shell查询验证)
- 若需仅展示已发布商品,可将查询语句改为
Product.objects.filter(is_published=True)(因is_published字段默认值为False)
内容的提问来源于stack exchange,提问作者Folium
相关产品推荐
相关产品推荐

