我的 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/