djangoTest/polls/views.py

41 lines
1.6 KiB
Python

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.db.models import F
from .models import Question, Choice
# Create your views here.
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)
# get all the choices and their votes
choices = question.choice_set.all()
max = 0
for choice in choices:
if choice.votes > max:
max = choice.votes
choice_data = [(choice.choice_text, choice.votes, choice.votes / max * 100) for choice in choices]
return render(request, "polls/results.html", {"question": question, "max_votes": max, "choices": choice_data})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = 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 = F("votes") + 1
selected_choice.save()
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))