First views

This commit is contained in:
Ludovic Stephan 2020-11-20 17:46:53 +01:00
parent d8b35e3be3
commit 466d95a10b
2 changed files with 50 additions and 0 deletions

8
elections/urls.py Normal file
View file

@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path("create/", views.ElectionCreateView.as_view(), name="election.create"),
path("update/<int:pk>", views.ElectionUpdateView.as_view(), name="election.update"),
path("view/<int:pk>", views.ElectionView.as_view(), name="election.view"),
]

42
elections/views.py Normal file
View file

@ -0,0 +1,42 @@
from django.views.generic import CreateView, UpdateView, DetailView
from django.contrib.messages.views import SuccessMessageMixin
from django.utils.translation import gettext_lazy as _
from django.db.models import Count, Prefetch
from .models import Election, Question, Option
# TODO: access control *everywhere*
class ElectionCreateView(SuccessMessageMixin, CreateView):
model = Election
fields = ["name", "description", "start_time", "end_time"]
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
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.election.tallied:
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):
return super().get_queryset().filter(archived=False).select_related("questions")