从模板中的视图访问时,投票的选择未显示

Poll's choices are not showing while accessing from view in template

我正在构建一个投票应用程序,但遇到了一个问题。

我正在尝试做什么:-

我正在尝试从 template 中的 view 访问 all three choices of poll,但只显示一个选项。但是当我在视图中访问 Poll 对象并从模板访问选择模型时,所有三个选择都成功显示。

models.py

class Poll(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    title = models.TextField()

    def get_absolute_url(self):
        return reverse('detail_poll', kwargs={'pk': self.pk})

class Choice(models.Model):
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=30)

forms.py

class PollAddForm(forms.ModelForm):
    choice1 = forms.CharField(label='Choice 1',max_length=100,min_length=2)
    choice2 = forms.CharField(label='Choice 2',max_length=100,min_length=2)
    choice3 = forms.CharField(label='Choice 3',max_length=100,min_length=2)

    class Meta:
        model = Poll
        fields = ['title','choice1', 'choice2', 'choice3']

我正在增加 forms 的选择。

views.py


def detail_poll(request,poll_id):
    poll = get_object_or_404(Poll, id=poll_id)

    for choice in poll.choice_set.all():
        printChoice = choice.choice_text

    context = {
        'printChoice ':printChoice ,
    }

    return render(request, 'detail_poll.html',context)

鉴于我正在访问 pollchoice_text 中的所有选项。 我在模板中使用相同的 (choice_set) 方法访问三个投票选项。

AND 当我创建投票时,投票成功保存了所有三个选项。当我投票时,民意调查成功投票。

但是当我访问选项以从视图中计算百分比时,选项没有显示。 使用模板中 poll.choice_text.all 的相同方法,它确实有效,但在视图中无效。

如有任何帮助,我们将不胜感激。

提前致谢。

它只显示一个选项,因为您只向上下文发送一个选项。即最后的选择。 彻底检查您的视图。for-loop 停止时,printChoice 将有最后的选择,您正在将其发送到上下文。所以模板中只会显示一个选项。

您应该遍历这些选择,将它们保存到数据结构中,例如 dictsetlist 等,然后将其发送到上下文。

应该是这样的。我使用了一个列表来存储 choice_texts 并将其传递给 context.

def detail_poll(request,poll_id):
    poll = get_object_or_404(Poll, id=poll_id)
    choice_set = []
    for choice in poll.choice_set.all():
        choice_set.append(choice.choice_text)
     
   # You can use your percentage calculation here...

    context = {
        'printChoice ': choice_set ,
    }

    return render(request, 'detail_poll.html',context)

您也可以像这样将整个查询集发送到 context

context = { 'printChoice': poll.choice_set.all() }

然后在template中,像这样显示choice_text

{% for choice in printChoice %} 
  <p>choice.choice_text</p>
{% endfor %}