[READ-ONLY] Mirror of https://github.com/shuuji3/django-tutorial.
0

Configure Feed

Select the types of activity you want to include in your feed.

rewrite the view to use generic views

+39 -4
+39 -4
mysite/polls/views.py
··· 1 - from django.shortcuts import render 2 - from django.http import HttpResponse 1 + from django.shortcuts import get_object_or_404, render 2 + from django.http import HttpResponseRedirect 3 + from django.urls import reverse 4 + from django.views import generic 5 + 6 + from .models import Choice, Question 7 + 8 + 9 + class IndexView(generic.ListView): 10 + template_name = 'polls/index.html' 11 + context_object_name = 'latest_question_list' 12 + 13 + def get_queryset(self): 14 + '''Return the last five published questions.''' 15 + return Question.objects.order_by('-pub_date')[:5] 16 + 17 + 18 + class DetailView(generic.DetailView): 19 + model = Question 20 + template_name = 'polls/detail.html' 21 + 22 + 23 + class ResultsView(generic.DetailView): 24 + model = Question 25 + template_name = 'polls/results.html' 3 26 4 27 5 - def index(request): 6 - return HttpResponse("Hello, world. You're at the polls index.") 28 + def vote(request, question_id): 29 + question = get_object_or_404(Question, pk=question_id) 30 + try: 31 + selected_choice = question.choice_set.get(pk=request.POST['choice']) 32 + except (KeyError, Choice.DoesNotExist): 33 + # Redisplay the question voting form with error_message 34 + return render(request, 'polls/detail.html', { 35 + 'question': question, 36 + 'error_message': "You didn't select a choice.", 37 + }) 38 + else: 39 + selected_choice.votes += 1 40 + selected_choice.save() 41 + return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))