Only allow one vote per client session
This commit is contained in:
parent
474b551e13
commit
5e60280e5e
@ -1,4 +1,4 @@
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.shortcuts import render, get_object_or_404, redirect
|
||||
from django.http import HttpResponse, HttpResponseRedirect
|
||||
from django.urls import reverse
|
||||
from django.db.models import F
|
||||
@ -13,6 +13,8 @@ def index(request):
|
||||
|
||||
def detail(request, question_id):
|
||||
question = get_object_or_404(Question, pk=question_id)
|
||||
if str(question_id) in request.session.get('votes', {}):
|
||||
return redirect(f'/polls/{question_id}/results')
|
||||
return render(request, "polls/detail.html", {"question": question})
|
||||
|
||||
|
||||
@ -30,6 +32,10 @@ def results(request, question_id):
|
||||
|
||||
def vote(request, question_id):
|
||||
question = get_object_or_404(Question, pk=question_id)
|
||||
votes = request.session.get('votes', {})
|
||||
if str(question_id) in votes:
|
||||
print("yes")
|
||||
return redirect(f'/polls/{question_id}/results')
|
||||
try:
|
||||
selected_choice = question.choice_set.get(pk=request.POST["choice"])
|
||||
except (KeyError, Choice.DoesNotExist):
|
||||
@ -38,4 +44,8 @@ def vote(request, question_id):
|
||||
else:
|
||||
selected_choice.votes = F("votes") + 1
|
||||
selected_choice.save()
|
||||
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
|
||||
|
||||
votes[question_id] = selected_choice.id
|
||||
request.session['votes'] = votes
|
||||
request.session.modified = True
|
||||
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user