我在我的models.py
:
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
is_active = models.BooleanField(default=True)
# The rest of code...
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
# The rest of code...
class Voter(models.Model):
user = models.ForeignKey(User)
poll = models.ForeignKey(Poll)
我vote
认为views.py
:
@login_required
def vote(request, poll_id):
# Some code...
# And here is the checking happens.
voters = [user.id for user in Voter.objects.filter(poll__id=poll_id)]
if request.user.id in voters:
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "Sorry, but you have already voted."
})
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice."
})
else:
selected_choice.votes +=1
selected_choice.save()
v = Voter(user=request.user, poll=p)
v.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
但是这段代码有点奇怪。
为了测试目的,我创建了 5 个民意调查。并且此代码仅适用于其中之一。 只有在其中一次投票中,当我尝试投票两次时才会收到错误消息。在本次投票的其余部分中,代码提供了根据需要进行多次投票的机会。
我不知道为什么。你有什么想法?