Django 模板未渲染相关模型的文本

问题描述 投票:0回答:1

我目前正在阅读官方 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
具有两个相关选项的问题模型呈现为

text from Questions model rendered correctly but elements from Choice model are not


我期望从

{% for question in question.choice_set.all %}
获得的相关 Choice 对象以列表元素的形式显示在 HTML 页面上。相反,仅显示项目符号而没有文本。

非常感谢任何帮助!

html django django-models django-views django-templates
1个回答
0
投票

您输入错误,您应该将其分配给

choice
变量:

<!--     🖟 choice -->
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.