You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
2.0 KiB

from django.db.models import Count
from django.shortcuts import render, get_object_or_404
from polls.models import Poll, Option, Vote
def polls(
request,
):
context = {}
context["polls"] = Poll.objects.all()
return render(
request,
template_name="polls/polls.html",
context=context,
)
def already_voted(
user,
poll,
):
vote = Vote.objects.filter(
poll=poll,
user=user,
)
return vote.exists()
def poll_results(
request,
poll_id,
):
context = {}
poll = get_object_or_404(
Poll,
pk=poll_id,
)
context["poll"] = poll
results = Vote.objects.filter(
poll=poll,
).annotate(
count=Count("option")
)
context["results"] = results
return render(
request,
template_name="polls/poll_results.html",
context=context,
)
def poll_details(
request,
poll_id,
):
poll = get_object_or_404(
Poll,
pk=poll_id,
)
if already_voted(
request.user,
poll,
):
return poll_results(
request,
poll_id,
)
context = {}
context["poll"] = poll
context["options"] = Option.objects.filter(
poll=poll,
)
return render(
request,
template_name="polls/poll_details.html",
context=context,
)
def cast_vote(
request,
poll_id,
option_id,
):
poll = get_object_or_404(
Poll,
pk=poll_id,
)
vote = Vote.objects.filter(
poll=poll,
user=request.user,
)
if vote.exists():
return poll_results(
request,
poll_id=poll_id,
)
option = get_object_or_404(
Option,
pk=option_id,
)
vote = Vote()
vote.poll = poll
vote.option = option
vote.user = request.user
vote.save()
return poll_results(
request,
poll_id=poll_id,
)

Powered by TurnKey Linux.