- allow voting by clicking an option on poll details page
- show results page after (or when selecting a poll, or trying to re-vote)
main
Guy Davis 9 months ago
parent 43eefd6bc1
commit ee7a8335b7

@ -4,7 +4,10 @@
</div>
<div>
{% for option in options %}
<div>
<div
hx-post="{% url 'cast-vote' poll.pk option.pk %}"
hx-target="#poll-details"
>
Option: {{ option.text }}
</div>
{% empty %}

@ -0,0 +1,14 @@
<div>
<div>
{{ poll.question }}
</div>
<div>
{% for result in results %}
<div>
{{ result.option.text }} - {{ result.count }}
</div>
{% empty %}
No options defined for Question!
{% endfor %}
</div>
</div>

@ -1,6 +1,6 @@
from django.urls import path
from polls.views import polls, poll_details
from polls.views import polls, poll_details, cast_vote
urlpatterns = [
path(
@ -13,4 +13,9 @@ urlpatterns = [
poll_details,
name="poll-details",
),
path(
"<int:poll_id>/vote/<int:option_id>",
cast_vote,
name="cast-vote",
),
]

@ -1,6 +1,7 @@
from django.db.models import Count
from django.shortcuts import render, get_object_or_404
from polls.models import Poll, Option
from polls.models import Poll, Option, Vote
def polls(
@ -17,6 +18,44 @@ def polls(
)
def already_voted(
user,
poll,
):
vote = Vote.objects.filter(
poll=poll,
user=user,
)
return vote.exists()
def poll_results(
request,
poll_id,
):
context = {}
poll = get_object_or_404(
Poll,
pk=poll_id,
)
context["poll"] = poll
results = Vote.objects.filter(
poll=poll,
).annotate(
count=Count("option")
)
context["results"] = results
return render(
request,
template_name="polls/poll_results.html",
context=context,
)
def poll_details(
request,
poll_id,
@ -26,6 +65,15 @@ def poll_details(
pk=poll_id,
)
if already_voted(
request.user,
poll,
):
return poll_results(
request,
poll_id,
)
context = {}
context["poll"] = poll
@ -38,3 +86,40 @@ def poll_details(
template_name="polls/poll_details.html",
context=context,
)
def cast_vote(
request,
poll_id,
option_id,
):
poll = get_object_or_404(
Poll,
pk=poll_id,
)
vote = Vote.objects.filter(
poll=poll,
user=request.user,
)
if vote.exists():
return poll_results(
request,
poll_id=poll_id,
)
option = get_object_or_404(
Option,
pk=option_id,
)
vote = Vote()
vote.poll = poll
vote.option = option
vote.user = request.user
vote.save()
return poll_results(
request,
poll_id=poll_id,
)

Loading…
Cancel
Save

Powered by TurnKey Linux.