3

我在我的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 个民意调查。并且此代码仅适用于其中之一。 只有在其中一次投票中,当我尝试投票两次时才会收到错误消息。在本次投票的其余部分中,代码提供了根据需要进行多次投票的机会。

我不知道为什么。你有什么想法?

4

1 回答 1

9

Voterid 不一定适合您的Userid。This explains why you see it sometimes appear to work (when voter id and user id accidentally match up). 代替:

voters = [user.id for user in Voter.objects.filter(poll__id=poll_id)]
if request.user.id in voters:

if Voter.objects.filter(poll_id=poll_id, user_id=request.user.id).exists()

让数据库后端为您进行检查是更好的做法。

于 2013-09-18T19:39:42.300 回答