Search code examples
htmldjangodjango-modelsdjango-viewsdjango-templates

Django template not rendering related model's text


I'm currently on the third part of the official Django polls tutorial. Have a problem where when I load the template detail.html, question_text from the Question model is being rendered fine but choice_text(s) are not. The browser shows the correct amount of list bullets as but the text is not there.

Here is the template I am trying to load:

<h1>{{ question.question_text }}</h1>

<ul>
    {% for question in question.choice_set.all %}
        <li> {{choice.choice_text}} </li>
    {% endfor %}
</ul>

The associated view function is:

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {'question': question})

The models are defined as:

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 the Question model with two Choices related to it is rendered as

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


I expected the related Choice objects obtained from {% for question in question.choice_set.all %} to display onto the HTML page as list elements. Instead only the bullets show up without the text.

Would really appreciate any help!


Solution

  • You made a typo, you should assign it to the choice variable:

    <!--     🖟 choice -->
    {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }}</li>
    {% endfor %}