作者:mobiledu2502900677 | 来源:互联网 | 2023-09-15 20:27
ImtryingtosetupavotingsysteminusingDjangothatlimitsaregisteredusertovotingonlyon
I'm trying to set up a voting system in using Django that limits a registered user to voting only once on a single vote (despite there being multiple options available agree/strongly agree/disagree). So far, I've been able to set up a system where they can't make the same exact vote (so they can't vote "agree" twice), but they can change their vote and it still goes through (so they can vote "agree" and then vote again as "disagree"). I want them to be limited to one vote per topic, and I can't quite figure out how to tweak my code to accomplish this. Here is my view:
我正在尝试建立一个使用Django的投票系统,限制注册用户在一次投票时只投票一次(尽管有多个选项可用/非常同意/不同意)。到目前为止,我已经能够建立一个他们无法进行同样投票的系统(所以他们不能投票“同意”两次),但是他们可以改变他们的投票并且它仍然可以通过(所以他们可以投票“同意”,然后再次投票为“不同意”)。我希望他们每个主题限制为一票,而我无法弄清楚如何调整我的代码来实现这一目标。这是我的观点:
def vote(request, prediction_id):
prediction = get_object_or_404(Prediction, pk=prediction_id)
selected_choice = prediction.choice_set.get(pk=request.POST['choice'])
if Voter.objects.filter(prediction=prediction, choice=selected_choice, user_id=request.user.id).exists():
return render(request, 'predictions/detail.html', {
'prediction': prediction,
'error_message': "Sorry, but you have already voted."
})
else:
selected_choice.votes += 1
selected_choice.save()
Voter.objects.create(prediction=prediction, choice=selected_choice, user_id=request.user.id)
return HttpResponseRedirect(reverse('predictions:results', args=(prediction.id,)))
and here are my models:
这是我的模特:
class Prediction(models.Model):
prediction_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
# ...
def __str__(self):
return self.prediction_text
class Choice(models.Model):
prediction = models.ForeignKey(Prediction, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Voter(models.Model):
user = models.ForeignKey(User)
choice = models.ForeignKey(Choice)
prediction = models.ForeignKey(Prediction)
1 个解决方案