Coverage for polls/views.py: 72.73%
33 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-23 10:02 -0700
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-23 10:02 -0700
1from django.contrib.auth.mixins import LoginRequiredMixin 1a
2from django.db.models import F 1a
3from django.http import HttpResponseRedirect 1a
4from django.shortcuts import get_object_or_404, render 1a
5from django.urls import reverse 1a
6from django.utils import timezone 1a
7from django.views.generic import DetailView, ListView 1a
9from .models import Choice, Question 1a
12class PollListView(LoginRequiredMixin, ListView): 1a
13 template_name = "polls/poll_list.html" 1a
14 context_object_name = "latest_question_list" 1a
16 def get_queryset(self): 1a
17 """
18 Return the last five published questions (not including
19 those set to be published in the future.
20 """
21 return Question.objects.filter(pub_date__lte=timezone.now()).order_by( 1a
22 "-pub_date"
23 )[:5]
26class PollDetailView(LoginRequiredMixin, DetailView): 1a
27 model = Question 1a
28 template_name = "polls/poll_detail.html" 1a
30 def get_queryset(self): 1a
31 """
32 Excludes any questions that aren't published yet.
33 """
34 return Question.objects.filter(pub_date__lte=timezone.now()) 1a
37class PollResultsView(DetailView, LoginRequiredMixin): 1a
38 model = Question 1a
39 template_name = "polls/poll_results.html" 1a
41 def get_queryset(self): 1a
42 """
43 Excludes any questions that aren't published yet.
44 """
45 return Question.objects.filter(pub_date__lte=timezone.now()) 1a
48def vote(request, question_id): 1a
49 question = get_object_or_404(Question, pk=question_id)
50 try:
51 selected_choice = question.choice_set.get(pk=request.POST["choice"])
52 except (KeyError, Choice.DoesNotExist):
53 # Redisplay the question voting form.
54 return render(
55 request,
56 "polls/poll_detail.html",
57 {
58 "question": question,
59 "error_message": "You didn't select a choice.",
60 },
61 )
62 else:
63 selected_choice.votes = F("votes") + 1
64 selected_choice.save()
65 """
66 Always return an HttpResponseRedirect after successfully
67 dealing with POST data. This prevents data from being posted
68 twice if a user hits the Back Button.
69 """
70 return HttpResponseRedirect(reverse("poll_results", args=(question.id,)))