- 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 7 months ago
parent 43eefd6bc1
commit ee7a8335b7

@ -4,7 +4,10 @@
</div> </div>
<div> <div>
{% for option in options %} {% for option in options %}
<div> <div
hx-post="{% url 'cast-vote' poll.pk option.pk %}"
hx-target="#poll-details"
>
Option: {{ option.text }} Option: {{ option.text }}
</div> </div>
{% empty %} {% 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 django.urls import path
from polls.views import polls, poll_details from polls.views import polls, poll_details, cast_vote
urlpatterns = [ urlpatterns = [
path( path(
@ -13,4 +13,9 @@ urlpatterns = [
poll_details, poll_details,
name="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 django.shortcuts import render, get_object_or_404
from polls.models import Poll, Option from polls.models import Poll, Option, Vote
def polls( 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( def poll_details(
request, request,
poll_id, poll_id,
@ -26,6 +65,15 @@ def poll_details(
pk=poll_id, pk=poll_id,
) )
if already_voted(
request.user,
poll,
):
return poll_results(
request,
poll_id,
)
context = {} context = {}
context["poll"] = poll context["poll"] = poll
@ -38,3 +86,40 @@ def poll_details(
template_name="polls/poll_details.html", template_name="polls/poll_details.html",
context=context, 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.