【发布时间】:2022-08-05 22:46:27
【问题描述】:
我有一个简单的投票应用程序。
models:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(\'date published\')
def __str__(self):
return self.question_text
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
results.html:
{% extends \'base.html\' %}
{% block content %}
<h1 class=\"mb-5 text-center\">{{ question.question_text }}</h1>
<ul class=\"list-group mb-5\">
{% for choice in question.choice_set.all %}
<li class=\"list-group-item\">
{{ choice.choice_text }} <span class=\"badge badge-success float-right\">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
</li>
{% endfor %}
</ul>
<a class=\"btn btn-secondary\" href=\"{% url \'polls:index\' %}\">Back To Polls</a>
<a class=\"btn btn-dark\" href=\"{% url \'polls:detail\' question.id %}\">Vote again?</a>
{% endblock %}
views.py:
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST[\'choice\'])
except (KeyError, Choice.DoesNotExist):
return render(request, \'polls/detail.html\', {
\'question\': question,
\'error_message\': \"You didn\'t select a choice.\",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse(\'polls:results\', args=(question.id,)))
如何为每个question 制作total 的投票数,以便您可以在底部显示total: 和此投票的总投票数。
-
你能分享你的观点吗,你可以使用
model.objects.count()。
标签: python django django-models django-views django-templates