My models.py is this and I have created the user registration form. I want to restrict one vote for one user. How Can I do so?
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)
My views.py is this for vote
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,)))
You should add a Vote
model
class Vote(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, unique=True)
choice = models.ForeignKey(Choice)
But i think maybe a more complete idea would be
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.