我目前正在阅读官方 Django 民意调查教程的第三部分。有一个问题,当我加载模板
detail.html
时,问题模型中的 question_text
渲染得很好,但 choice_text
却没有。浏览器显示正确数量的列表项目符号,但文本不存在。
<h1>{{ question.question_text }}</h1>
<ul>
{% for question in question.choice_set.all %}
<li> {{choice.choice_text}} </li>
{% endfor %}
</ul>
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, "polls/detail.html", {'question': question})
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
polls/1
具有两个相关选项的问题模型呈现为我期望从
{% for question in question.choice_set.all %}
获得的相关 Choice 对象以列表元素的形式显示在 HTML 页面上。相反,仅显示项目符号而没有文本。
非常感谢任何帮助!
您输入错误,您应该将其分配给
choice
变量:
<!-- 🖟 choice -->
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}