Django4视图返回数据无法在index.html模板正常渲染
问题排查与修复
数据无法正常渲染由3个基础代码错误导致,按以下步骤修改即可解决:
- 模板for循环迭代对象名错误:视图传给模板的上下文键是小写
appartement(对应所有公寓的查询结果集),你写的大写Appartement是模型类,没有传入模板上下文,循环根本不会执行 - 循环内变量引用错误:for循环中已经给单个公寓实例起了别名
appartement,你内部取字段全用了大写的模型类名Appartement,无法读取实例的字段值 - 模型
__str__方法字段名错误:模型中公寓名称字段是nom,方法里写的self.name不存在,访问模型实例时会直接抛出属性错误
1. 修正models.py
仅需修改__str__方法的返回字段,该修改不涉及表结构变更,无需执行数据库迁移:
class Appartement(models.Model): nom = models.CharField(max_length=200) Ville_et_adresse = models.CharField(max_length=200) NB_de_chambre = models.DecimalField(max_digits=20, decimal_places=0) NB_de_douche = models.DecimalField(max_digits=20, decimal_places=0) NB_de_garage = models.DecimalField(max_digits=20, decimal_places=0) NB_de_piscine = models.DecimalField(max_digits=20, decimal_places=0) NB_de_cuisine = models.DecimalField(max_digits=20, decimal_places=0) Superficie = models.DecimalField(max_digits=20, decimal_places=0) Prix = models.DecimalField(max_digits=20, decimal_places=0) Description = models.TextField(max_length=1000, default=True) image = models.ImageField(upload_to="static/upload/", blank=True, null=True) actif = models.BooleanField(default=True) def __str__(self): # 原代码错误引用了不存在的name字段,改为已定义的nom字段 return f'{self.nom}' class Meta: ordering = ['-id'] verbose_name_plural =("Appartements")
2. 修正index.html模板
修改循环对象名、内部变量名,额外添加空状态判断方便排查无数据场景:
<div class="property-item"> <a class="property-img" href="avendre"> <img src="{% static 'images/property/property_1.jpg'%}" alt="#"> </a> ... </div> <!-- 修正迭代对象为视图传入的appartement查询集 --> {% for appartement in appartement %} <div class="property-title-box"> <h4><a href="avendre">{{ appartement.nom }}</a></h4> <div class="property-location"> <i class="fa fa-map-marker-alt"></i> <!-- 修正变量名为循环的单个实例appartement --> <p>{{ appartement.Ville_et_adresse}}</p> </div> <ul class="property-feature"> <li> <i class="fas fa-bed"></i> <span>{{ appartement.NB_de_chambre }}</span> </li> <li> <i class="fas fa-bath"></i> <span>{{ appartement.NB_de_douche }}</span> </li> <li> <i class="fas fa-arrows-alt"></i> <span>{{ appartement.Superficie }}</span> </li> <li> <i class="fas fa-car"></i> <!-- 注意:此处图标为车辆标识,对应车库字段应为appartement.NB_de_garage,当前取的是泳池数量属于逻辑错误,可按需调整 --> <span>{{ appartement.NB_de_piscine }}</span> </li> </ul> <div class="trending-bottom"> <a class="trend-left float-left"> <div class="trend-open"> <p>{{ appartement.Prix }}</p> </div> </a> </div> </div> {% empty %} <!-- 查询集为空时显示提示,方便快速排查问题 --> <p>暂无已发布的公寓信息</p> {% endfor %}
额外注意事项
如果后续需要渲染模型中image字段上传的房产图片,需要在项目配置中补充MEDIA_URL、MEDIA_ROOT设置,并在根路由中添加媒体文件的访问路由,否则图片无法正常加载。
内容的提问来源于stack exchange,提问作者oue serge Gedeon
相关产品推荐
相关产品推荐

