views.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. # Create your views here.
  8. class IndexView(generic.ListView):
  9. template_name = "polls/index.html"
  10. context_object_name = "latest_question_list"
  11. def get_queryset(self):
  12. """Return the last five poblished questions."""
  13. return Question.objects.order_by("-pub_date")[:5]
  14. class DetailView(generic.DetailView):
  15. model = Question
  16. template_name = "polls/detail.html"
  17. class ResultsView(generic.DetailView):
  18. model = Question
  19. template_name = "polls/results.html"
  20. def vote(request, question_id):
  21. question = get_object_or_404(Question, pk=question_id)
  22. try:
  23. selected_choice = question.choice_set.get(pk=request.POST["choice"])
  24. except (KeyError, Choice.DoesNotExist):
  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,)))