views.py 1.7 KB

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