views.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
from django.utils import timezone
Create your views here.
class IndexView(generic.ListView):
templates_name = âpolls/index.htmlâ
context_object_name = âlatest_question_listâ
def get_queryset(self):
"""return the last five published questions."""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
templates_name = âpolls/detail.htmlâ
class ResultsView(generic.DetailView):
model = Question
templates_name = âpolls/results.htmlâ
def index(request):
latest_question_list = Question.objects.order_by(â-pub_dateâ)[:5]
context = {
âlatest_question_listâ: latest_question_list,
}
return render(request, âpolls/index.htmlâ, context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, âpolls/detail.htmlâ, {âquestionâ: question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, âpolls/results.htmlâ, {âquestionâ: question})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.question.choice_set.get(pk=request.POST[âchoiceâ])
except (KeyError, Choice.DoesNotExist):
return render(request, âpolls/detail.htmlâ, {
âquestionâ: question,
âerror_messageâ: âYou didnât select a choiceâ,
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse(âpolls:resultsâ, args=(question.id,)))
def get_queryset():
return Question.objects.filter(pub_date__lte=timezone.now())