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.

170 lines
3.0 KiB

from chartkick.django import PieChart
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.shortcuts import render, get_object_or_404
from django.views.decorators.csrf import requires_csrf_token
from polls.models import Poll, Option, Vote
@login_required
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()
@login_required
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,
).values(
"option",
).annotate(
count=Count("option"),
)
colors = [
"#dd966b",
"#a1b0f7",
"#ffd83d",
"#8ac3a3",
"#dec2cb",
]
legend = []
index = 0
for option in results:
legend.append(
{
"color": colors[index % len(colors)],
"option": Option.objects.get(pk=option["option"]).text,
"count": option["count"],
}
)
index += 1
chart_data = {
Option.objects.get(pk=option["option"]).text: option["count"]
for option in results
}
context["chart"] = PieChart(
data=chart_data,
width="384px",
height="384px",
legend=False,
colors=colors,
)
context["legend"] = legend
return render(
request,
template_name="polls/poll_results.html",
context=context,
)
@login_required
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,
).order_by(
"pk",
)
return render(
request,
template_name="polls/poll_details.html",
context=context,
)
@login_required
@requires_csrf_token
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.