Django民意测验 [英] Django polls with autentication

查看:41
本文介绍了Django民意测验的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用django从文档中的民意测验应用程序.我现在想使其先进.我不希望用户能够投票两次,这意味着用户只能投票一次,否则它将显示错误消息.如果登录的是超级用户,效果很好,但是对于其他任何用户,他们仍然可以多次投票.

I have a poll app using django from the docs. I now want to make it advanced. I dont want a user to be able to vote twice that means the users can only vote once else it would show an error message. It works fine if it is the super user that is logged in but for any other user, they are still able to vote multiple times.

模型

class Question(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='question_created')
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='choice_created')
    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

查看

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if Choice.objects.filter(question_id=question_id, user_id=request.user.id).exists():
        context = {
                'question': question,
                'error_message': "Sorry, but you have already voted.",
                }
        template = 'polls/detail.html'
        return render(request, template, context)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        context = {
                'question': question,
                'error_message': "You didn't select a choice.",
                }
        template = 'polls/detail.html'
        return render(request, template, context)
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

推荐答案

尝试在 else:语句内移动 try:除外:.

在" question_id "中添加2个下划线和" user_id "像这样的 Choice.objects.filter(question__id = question_id,user__id = request.user.id).exists()也许这就是为什么 if 语句每次都返回false的原因让您投票两次

add 2 underscores to "question_id" and "user_id" like this Choice.objects.filter(question__id=question_id, user__id=request.user.id).exists() maybe that's why the if statement returns false every time and it lets you vote twice

为了安全起见,您可以将 selected_choice.votes + = 1 更改为 selected_choice.votes = 1 ,以确保每条记录不超过一票.

Also just for safety, you can change selected_choice.votes += 1 to selected_choice.votes = 1 you want to ensure that each record doesn't exceed more than one vote.

希望有帮助!

这篇关于Django民意测验的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆