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, ).annotate( count=Count("option") ) colors = [ "#dd966b", "#a1b0f7", "#ffd83d", "#8ac3a3", "#dec2cb", ] legend = [] index = 0 for vote in results: legend.append( { "color": colors[index % len(colors)], "option": vote.option.text, "count": vote.count, } ) index += 1 chart_data = { vote.option.text: vote.count for vote 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, )