Coverage for polls/views.py: 72.73%

33 statements  

« prev     ^ index     » next       coverage.py v7.8.2, created at 2025-06-08 13:12 -0700

1from django.contrib.auth.mixins import LoginRequiredMixin 

2from django.db.models import F 

3from django.http import HttpResponseRedirect 

4from django.shortcuts import get_object_or_404, render 

5from django.urls import reverse 

6from django.utils import timezone 

7from django.views.generic import DetailView, ListView 

8 

9from .models import Choice, Question 

10 

11 

12class PollListView(LoginRequiredMixin, ListView): 

13 template_name = "polls/poll_list.html" 

14 context_object_name = "latest_question_list" 

15 

16 def get_queryset(self): 

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( 1bcdef

22 "-pub_date" 

23 )[:5] 

24 

25 

26class PollDetailView(LoginRequiredMixin, DetailView): 

27 model = Question 

28 template_name = "polls/poll_detail.html" 

29 

30 def get_queryset(self): 

31 """ 

32 Excludes any questions that aren't published yet. 

33 """ 

34 return Question.objects.filter(pub_date__lte=timezone.now()) 1gh

35 

36 

37class PollResultsView(DetailView, LoginRequiredMixin): 

38 model = Question 

39 template_name = "polls/poll_results.html" 

40 

41 def get_queryset(self): 

42 """ 

43 Excludes any questions that aren't published yet. 

44 """ 

45 return Question.objects.filter(pub_date__lte=timezone.now()) 1ij

46 

47 

48def vote(request, question_id): 

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,)))