python - 如何限制一名用户投一票?

标签 python django django-models django-forms django-templates

我的 models.py 是这样的,我已经创建了用户注册表单。我想限制一名用户投一票。我怎样才能这样做?

class Choice(models.Model):
    choice_text = models.CharField(max_length= 200)
    votes = models.IntegerField(default= 0)
    image2 = models.ImageField(upload_to="Question_Image2", blank=True)
    question = models.ForeignKey(Question, on_delete= models.CASCADE)

    def __str__(self):
        return  self.choice_text

    def vote_range(self):
        return range(0, self.votes)

我的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:
        return render(request, 'polls/detail.html', {'question':question, 'error_message':"Please select a choice"})
    else:
        selected_choice.votes += 1
        selected_choice.save()

        return HttpResponseRedirect(reverse('polls:results',args = (question.id,)))

最佳答案

您应该添加一个投票模型

class Vote(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, unique=True)
    choice = models.ForeignKey(Choice)

但我认为也许更完整的想法是

class Vote(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User
    choice = models.ForeignKey(Choice)
    election = models.ForeignKey(Election)

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

关于python - 如何限制一名用户投一票?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48718704/

相关文章:

python - 在 Windows 上安装 GeoIP?

sql - ManyToManyField 中 Django 中对象子集的不同值

mysql - 在 Django 中加载固定装置时出现内容类型问题

python - 使用 selenium 和 bs4 进行网页抓取

Python 预期 : fdpexpect + pyserial == timeout does not work?

python:使用一个类来跟踪另一个类使用的数据

python - Django:自定义用户模型字段未出现在 Django 管理中

python - 在python响应中显示非英文字符

sql - 使用 sql 数据创建模型

django - 使用 Django Model 类继承为表创建审核日志