diff --git a/polls/templates/polls/poll_details.html b/polls/templates/polls/poll_details.html index 19af3af..b962c32 100644 --- a/polls/templates/polls/poll_details.html +++ b/polls/templates/polls/poll_details.html @@ -4,7 +4,10 @@
{% for option in options %} -
+
Option: {{ option.text }}
{% empty %} diff --git a/polls/templates/polls/poll_results.html b/polls/templates/polls/poll_results.html new file mode 100644 index 0000000..456af33 --- /dev/null +++ b/polls/templates/polls/poll_results.html @@ -0,0 +1,14 @@ +
+
+ {{ poll.question }} +
+
+ {% for result in results %} +
+ {{ result.option.text }} - {{ result.count }} +
+ {% empty %} + No options defined for Question! + {% endfor %} +
+
\ No newline at end of file diff --git a/polls/urls.py b/polls/urls.py index bb965cd..04dfeac 100644 --- a/polls/urls.py +++ b/polls/urls.py @@ -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( + "/vote/", + cast_vote, + name="cast-vote", + ), ] diff --git a/polls/views.py b/polls/views.py index bd7803f..83bf9b3 100644 --- a/polls/views.py +++ b/polls/views.py @@ -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, + )