views.py 1.62 KB
Newer Older
fred's avatar
fred committed
1 2 3
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
fred's avatar
fred committed
4
from django.views.generic.list import ListView
fred's avatar
fred committed
5 6 7 8 9 10 11 12
from django.contrib import messages

from .models import Vote

class VoteView(TemplateView):
    template_name = 'vote.html'

    def dispatch(self, request, *args, **kwargs):
fred's avatar
fred committed
13
        return redirect('home')
fred's avatar
fred committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
        try:
            vote = Vote.objects.get(user=request.user)
            messages.error(request, 'Non !')
            return redirect('home')
        except Vote.DoesNotExist:
            pass
        return super(VoteView, self).dispatch(request, *args, **kwargs)

    def post(self, request):
        choice = request.POST['choice']
        comment = request.POST['comment']

        vote = Vote(
                user=request.user,
                choice=request.POST['choice'],
                comment=request.POST['comment'])
        vote.save()
        messages.success(request, 'Merci !')
        return redirect('home')

vote = login_required(VoteView.as_view())
fred's avatar
fred committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51


class ResultsView(ListView):
    model = Vote
    template_name = 'vote_results.html'

    def get_queryset(self):
        return Vote.objects.order_by('?')

    def get_context_data(self, **kwargs):
        context = super(ResultsView, self).get_context_data(**kwargs)
        context['choice_1'] = self.get_queryset().filter(choice="1").count()
        context['choice_2'] = self.get_queryset().filter(choice="2").count()
        context['choice_3'] = self.get_queryset().filter(choice="3").count()
        return context

vote_results = login_required(ResultsView.as_view())