使用无限期选项轮询应用程序,防止从显示的选项中进行投票

时间:2017-02-13 16:43:33

标签: python django

我正在研究一个django投票系统,你可以从一组候选人中显示一小部分随机选项,我提交投票的方式是使用选项的ID,但我想不到为了防止人们只是改变源代码并一遍又一遍地对同一选项提交投票,这些选项会显示在视图和模板上,如下所示:

  

return render(request,'/ return.html',{'p':po,'opts':   opts.order_by( '?')[:3]

    {%for v in opts%}
<div class='votebox' name='{{v.id}}' onclick='vote()'></div>
{%endfor%}

检查用户是否对显示给他们的选项投票的代码有效方法是什么?

投票选项模型就是这个

class Submission(models.Model):
    def __str__(self):
        return self.title

    title = models.CharField(max_length=20)
    signature = models.CharField(max_length=20)
    sub_date = models.DateField()
    poll = models.ForeignKey('Poll', on_delete=models.CASCADE)
    vote_count = models.IntegerField(null=True)
    img = models.ImageField(upload_to='MEDIA_ROOT')
    repcount = models.IntegerField()

民意调查模型是:

class Poll(models.Model):
    title = models.CharField(max_length=20)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    start_date = models.DateField()
    end_date=models.DateField()

以及它所在的视图是

def poll(request, id):
    if request.method == "GET":
        po = poll.objects.get(id=id)
        daysleft = poll.end_date - datetime.date.today()
        opts = po.submission_set.all()
        return render(request, '/vote.html', {'p': po, 'opts' : opts, 'daysl':daysleft}


    elif request.method == "POST":
        voted = request.POST.get('voteval', False)
        sub = Submission.objects.get(id=voted)
        sub.vote_count += 1
        sub.save()

1 个答案:

答案 0 :(得分:0)

我会在UserSubmission

之间添加中间模型
class Vote(models.Model):
    user = models.ForeignKey(User)
    submission = models.ForeignKey(Submission)

    class Meta:
        unique_together = (
            ('user', 'submission'),
        )

现在,在处理视图的POST部分时,您可以检查用户之前是否已对此提交进行了投票,并创建了新的Vote对象,如果他还没有

elif request.method == "POST":
        voted = request.POST.get('voteval', False)
        sub = Submission.objects.get(id=voted)
        user = request.user
        try:
            vote = Vote.objects.get(user=user, submission=sub)
            # warn user that he's voted for this submission
        except Vote.DoesNotExist:
            vote = Vote.objects.create(user=user, submission=sub)
            sub.vote_count += 1
            sub.save()