Django页面Topic显示正常但Entry无法加载问题求助
Django学习日志项目Entry数据无法显示问题排查
问题现象
页面链接可正常访问,数据库中的Topic名称能正常展示,但关联的Entry数据无法在页面上显示。
相关代码
views.py
from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """The home page for learning log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context)
topic.html
{% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic.text }}</p> <p>Entries:</p> <ul> {% for topic in topics %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %}
models.py
from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a simple string representation of the entry.""" return f"{self.text[:50]}..."
问题原因与修复
核心错误
模板topic.html的循环逻辑完全错误:
- 视图函数
topic传递给模板的上下文是{'topic': 单个话题对象, 'entries': 该话题的所有条目集合},模板中不存在topics这个变量 - 循环写了
{% for topic in topics %},既引用了不存在的变量,又把循环变量命名为topic(和当前话题变量重名) - 循环内部引用的
entry变量从未定义,导致无法渲染条目内容
修复后的topic.html
将循环部分修改为遍历上下文里的entries集合,循环变量使用entry:
{% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic.text }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %}
其他验证
- views.py的逻辑正确:通过
topic.entry_set.order_by('-date_added')正确获取了当前话题关联的所有条目并按添加时间倒序排列 - models.py的外键关联配置正确,Entry和Topic的一对多关系无误
内容的提问来源于stack exchange,提问作者Dokkaebi
相关产品推荐
相关产品推荐

