From 08c9f87398b1be219a10d86c2f7f78b43ff2d428 Mon Sep 17 00:00:00 2001 From: Lukas Date: Fri, 27 Aug 2021 21:28:27 +0200 Subject: [PATCH] pre rewrite to generic views --- djlearn/polls/templates/polls/detail.html | 18 ++++++++++------ djlearn/polls/templates/polls/results.html | 9 ++++++++ djlearn/polls/views.py | 24 +++++++++++++++++----- 3 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 djlearn/polls/templates/polls/results.html diff --git a/djlearn/polls/templates/polls/detail.html b/djlearn/polls/templates/polls/detail.html index 4e1bd67..0566bce 100644 --- a/djlearn/polls/templates/polls/detail.html +++ b/djlearn/polls/templates/polls/detail.html @@ -1,6 +1,12 @@ -

{{ question.question_text }}

- \ No newline at end of file +
+{% csrf_token %} +
+

{{ question.question_text }}

+ {% if error_message %}

{{ error_message }}

{% endif %} + {% for choice in question.choice_set.all %} + +
+ {% endfor %} +
+ +
\ No newline at end of file diff --git a/djlearn/polls/templates/polls/results.html b/djlearn/polls/templates/polls/results.html new file mode 100644 index 0000000..33b67b2 --- /dev/null +++ b/djlearn/polls/templates/polls/results.html @@ -0,0 +1,9 @@ +

{{ question.question_text }}

+ + + +Vote again? \ No newline at end of file diff --git a/djlearn/polls/views.py b/djlearn/polls/views.py index 9d42a1c..12e3b00 100644 --- a/djlearn/polls/views.py +++ b/djlearn/polls/views.py @@ -1,6 +1,8 @@ from django.shortcuts import render, get_object_or_404 -from django.http import HttpResponse -from .models import Question +from django.http import HttpResponse, HttpResponseRedirect +from django.urls import reverse + +from .models import Choice, Question # Create your views here. @@ -17,9 +19,21 @@ def detail(request, question_id): def results(request, question_id): - response = f"You're looking @ the results of question {question_id}" - return HttpResponse(response) + question = get_object_or_404(Question, pk=question_id) + return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): - return HttpResponse(f"You're voting on question {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): + # Redisplay the question voting form. + return render(request, 'polls/detail.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,)))