diff --git a/polls/templates/polls/detail.html b/polls/templates/polls/detail.html index 6778f30..e08d9f8 100644 --- a/polls/templates/polls/detail.html +++ b/polls/templates/polls/detail.html @@ -16,9 +16,8 @@ - -
+ {% comment %}
@@ -33,10 +32,10 @@
-
+ {% endcomment %} -
+
@@ -50,11 +49,6 @@
Please Select a Choice😊
- {% if error_message %} -
-

{{ error_message }}

-
- {% endif %}
@@ -71,7 +65,7 @@ {% endfor %}
- + diff --git a/polls/templates/polls/results.html b/polls/templates/polls/results.html index 2ecdf3a..9f9b845 100644 --- a/polls/templates/polls/results.html +++ b/polls/templates/polls/results.html @@ -25,7 +25,19 @@ -
+ +
+ {% for message in messages %} + {% if message.tags == 'success' %} +
+
+

{{ message }}

+
+
+
+ {% endif %} + {% endfor %}
diff --git a/polls/views.py b/polls/views.py index 40eaf83..9bef0b9 100644 --- a/polls/views.py +++ b/polls/views.py @@ -1,10 +1,12 @@ from django.http import HttpResponseRedirect -from django.shortcuts import get_object_or_404, render +from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.views import generic from django.utils import timezone -from django.urls import reverse_lazy +from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib import messages +from django.contrib.auth.decorators import login_required from .forms import SignUpForm from .models import Choice, Question @@ -73,26 +75,24 @@ class SignUpView(generic.CreateView): success_url = reverse_lazy('login') template_name = 'registration/signup.html' - +@login_required def vote(request, question_id): """ - A function that update the database. Add vote count to choice that user vote - in specific question_id. + A function that updates the database. Adds a vote count to the choice that the user votes for + in a specific question_id. """ - question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): - return render( - request, - "polls/detail.html", - { - "question": question, - "error_message": "You didn't select a choice.", - }, - ) + messages.error(request, "You didn't select a choice.") + return render(request, "polls/detail.html", {"question": question}) else: - selected_choice.votes += 1 - selected_choice.save() - return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) + if request.method == "POST" and "vote-button" in request.POST: + selected_choice.votes += 1 + selected_choice.save() + messages.success(request, "Your vote was recorded successfully🥳") + return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) + else: + messages.error(request, "You cannot vote by typing the URL.") + return render(request, "polls/detail.html", {"question": question})