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



我正在构建一个投票应用程序,我被困在一个问题上。

我想做什么:-

我试图从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时,poll成功地保存了所有三个选择。当我投票时,poll就成功地投票了。

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

任何帮助都将非常感激。

谢谢你提前。

它只显示一个选择,因为你只发送一个选择到上下文。也就是最后一个选择。彻底检查你的视图for-loop停止时,printChoice将拥有最后一个选择,您将其发送到上下文。因此,只有一个选择将在模板中显示。

你应该迭代的选择和保存它们的数据结构,如dict,set,list等,然后将其发送到上下文

应该是这样的。我已经使用了一个列表来存储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 %}

最新更新