Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

from rest_framework.generics import RetrieveAPIView 

from rest_framework.response import Response 

 

from django.contrib import messages 

from django.db import transaction 

from django.urls import reverse_lazy 

from django.views.generic import DetailView, ListView 

from django.views.generic.edit import CreateView 

 

from .forms import ChoiceFormSet, QuestionForm 

from .models import Choice, Question 

from .serializers import ChoiceSerializer 

 

 

class QuestionListView(ListView): 

queryset = Question.objects.all() 

context_object_name = 'questions' 

template_name = 'polls/list.html' 

 

def get_queryset(self): 

queryset = self.queryset.order_by('-id') 

return queryset 

 

 

class QuestionDetailView(DetailView): 

model = Question 

context_object_name = 'question' 

template_name = 'polls/detail.html' 

 

def get_context_data(self, **kwargs): 

data = super().get_context_data(**kwargs) 

data['choices'] = Choice.objects.filter(question_id=self.object.pk).order_by('pk') 

return data 

 

 

class QuestionCreateView(CreateView): 

form_class = QuestionForm 

template_name = 'polls/form.html' 

 

def get_context_data(self, **kwargs): 

data = super().get_context_data(**kwargs) 

42 ↛ 43line 42 didn't jump to line 43, because the condition on line 42 was never true if self.request.POST: 

data['choices'] = ChoiceFormSet(self.request.POST) 

else: 

data['choices'] = ChoiceFormSet() 

return data 

 

def form_valid(self, form): 

context = self.get_context_data() 

choices = context['choices'] 

with transaction.atomic(): 

form.instance.created_by = self.request.user 

self.object = form.save() 

if choices.is_valid(): 

choices.instance = self.object 

choices.save() 

messages.success(self.request, 'Question is created.') 

return super().form_valid(form) 

 

def get_success_url(self): 

return reverse_lazy('polls:detail', kwargs={'pk': self.object.pk}) 

 

 

class VoteView(RetrieveAPIView): 

queryset = Choice.objects.all() 

serializer_class = ChoiceSerializer 

 

def get(self, request, *args, **kwargs): 

choice = self.get_object() 

serializer = self.get_serializer(choice) 

choice.votes += 1 

choice.save() 

return Response(serializer.data)