我的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,)))
答案 0 :(得分:2)
您应该添加Vote
模型
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')