kadenios/elections/views.py

84 lines
2.8 KiB
Python
Raw Normal View History

from django.contrib import messages
2020-11-20 17:46:53 +01:00
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Count, Prefetch
2020-12-18 00:19:18 +01:00
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import CreateView, DetailView, UpdateView
2020-11-20 17:46:53 +01:00
2020-12-18 17:38:44 +01:00
from .forms import ElectionCreateForm, OptionFormSet
2020-12-18 00:19:18 +01:00
from .models import Election, Option, Question
2020-11-20 17:46:53 +01:00
# TODO: access control *everywhere*
class ElectionCreateView(SuccessMessageMixin, CreateView):
model = Election
2020-12-18 17:38:44 +01:00
form_class = ElectionCreateForm
2020-11-20 19:31:22 +01:00
template_name = "elections/election_create.html"
2020-11-20 17:46:53 +01:00
success_message = _("Élection crée avec succès !")
class ElectionUpdateView(SuccessMessageMixin, UpdateView):
model = Election
fields = ["name", "description", "start_time", "end_time"]
success_message = _("Élection modifiée avec succès !")
def get_queryset(self):
# On ne peut plus modifier une élection déjà comptée
return super().get_queryset().filter(tallied=False, archived=False)
class ElectionView(DetailView):
model = Election
2020-12-18 00:19:18 +01:00
template_name = "elections/election.html"
2020-11-20 17:46:53 +01:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
2020-12-18 00:19:18 +01:00
if self.object.tallied:
2020-11-20 17:46:53 +01:00
options_qs = Option.objects.annotate(nb_votes=Count("voters"))
questions = self.election.question.prefetch_related(
Prefetch("options", queryset=options_qs)
)
context["questions"] = questions
return context
def get_queryset(self):
2020-12-18 00:19:18 +01:00
return super().get_queryset().filter(archived=False)
class VoteView(SuccessMessageMixin, DetailView):
2020-12-18 00:19:18 +01:00
model = Question
template_name = "elections/vote.html"
def get_queryset(self):
# On ne peut voter que si l'élection n'a pas été comptée
return (
super()
.get_queryset()
.filter(election__tallied=False, election__archived=False)
.select_related("election")
)
def get(self, request, *args, **kwargs):
self.object = self.get_object()
vote_form = OptionFormSet(instance=self.object)
2020-12-18 17:38:44 +01:00
return self.render_to_response(self.get_context_data(formset=vote_form))
2020-12-18 00:19:18 +01:00
def post(self, request, *args, **kwargs):
self.object = self.get_object()
vote_form = OptionFormSet(self.request.POST, instance=self.object)
# We record the cast votes
for v in vote_form:
v.record_vote(self.request.user)
messages.success(self.request, _("Votre vote a bien été enregistré !"))
2020-12-18 00:19:18 +01:00
return HttpResponseRedirect(
reverse("election.view", args=[self.object.election.pk])
+ f"#q_{self.object.pk}"
)