From d9eb2540d92957d2c45efa8a08ff6663db5b63d4 Mon Sep 17 00:00:00 2001 From: ergz Date: Sat, 23 Jul 2022 22:56:41 -0700 Subject: [PATCH] adds a view for voting on a question --- db.sqlite3 | Bin 143360 -> 143360 bytes polls/models.py | 2 +- polls/templates/polls/details.html | 17 ++++++++++------- polls/urls.py | 2 ++ polls/views.py | 19 ++++++++++++++++--- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/db.sqlite3 b/db.sqlite3 index 5a7fb660756366826276b3893e66e278de0d9a91..2170b7ef8772024380e0bee9da07b505673dd02e 100644 GIT binary patch delta 142 zcmZp8z|ru4V}dlJ=|mZ4M$^WG)&$0_2~5lQ1?DmEf8u|_f0}z{PQ;p7Ig6Q z^02cqh%+*#7o{eaFil@A&*US|$(fg5l98F0&c(pMz{dZ8f&UNxcc9*9{15ow@ZSRJ lJHoHV|Av8$iJg_1k&%fFOtOMWb{1w%MrIJf#LUde2>}0wBRv2B delta 141 zcmZp8z|ru4V}dlJ(L@<%Mx(}r)&$0_2~5lQ1?DsGf8u|_f0}>Ah;uNe7o{eaOkXX}Question: -

{{ question.question_text }}

- -

Available Choices:

-
    +
    +{% csrf_token %} +
    +

    {{ question.question_text }}

    + {% if error_message %}

    {{ error_message }}

    {% endif %} {% for choice in question.choice_set.all %} -
  • {{ choice.choice_text }}
  • + +
    {% endfor %} -
\ No newline at end of file + + + \ No newline at end of file diff --git a/polls/urls.py b/polls/urls.py index 7271bc0..a31ddea 100644 --- a/polls/urls.py +++ b/polls/urls.py @@ -2,6 +2,8 @@ from django.urls import path from . import views +app_name = "polls" + urlpatterns = [ path("", views.index, name = "index"), path("", views.detail, name="detail"), diff --git a/polls/views.py b/polls/views.py index 3175a73..c981dc1 100644 --- a/polls/views.py +++ b/polls/views.py @@ -1,6 +1,7 @@ -from django.http import HttpResponse, Http404 +from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import loader -from django.shortcuts import render +from django.shortcuts import render, get_object_or_404 +from django.urls import reverse from .models import Question, Choice @@ -24,4 +25,16 @@ def results(request, question_id): return HttpResponse(response % question_id) def vote(request, question_id): - return HttpResponse("you are voting on question %s" % 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/details.html", { + "question": question, + "error_message": "You didn't select a choice!" + }) + else: + selected_choice.votes += 1 + selected_choice.save() + + return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) \ No newline at end of file