63 lines
1.7 KiB
Python
63 lines
1.7 KiB
Python
from django import forms
|
|
from django.forms.models import inlineformset_factory
|
|
from django.utils import timezone
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
from .models import Election, Option, Question
|
|
|
|
|
|
class ElectionForm(forms.ModelForm):
|
|
def clean(self):
|
|
cleaned_data = super().clean()
|
|
if cleaned_data["start_date"] < timezone.now():
|
|
self.add_error(
|
|
"start_date", _("Impossible de faire débuter l'élection dans le passé")
|
|
)
|
|
elif cleaned_data["start_date"] >= cleaned_data["end_date"]:
|
|
self.add_error(
|
|
"end_date", _("Impossible de terminer l'élection avant de la commencer")
|
|
)
|
|
return cleaned_data
|
|
|
|
class Meta:
|
|
model = Election
|
|
fields = ["name", "description", "start_date", "end_date"]
|
|
|
|
|
|
class QuestionForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Question
|
|
fields = ["text"]
|
|
|
|
|
|
class OptionForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Option
|
|
fields = ["text"]
|
|
|
|
|
|
class VoteForm(forms.ModelForm):
|
|
def __init__(self, **kwargs):
|
|
super().__init__(**kwargs)
|
|
# We set the option's text as the label for the checkbox
|
|
instance = kwargs.get("instance", None)
|
|
if instance is not None:
|
|
self.fields["selected"].label = instance.text
|
|
|
|
selected = forms.BooleanField(required=False)
|
|
|
|
def record_vote(self, user):
|
|
self.full_clean()
|
|
if self.cleaned_data["selected"]:
|
|
self.instance.voters.add(user)
|
|
else:
|
|
self.instance.voters.remove(user)
|
|
|
|
class Meta:
|
|
model = Option
|
|
fields = []
|
|
|
|
|
|
OptionFormSet = inlineformset_factory(
|
|
Question, Option, extra=0, form=VoteForm, can_delete=False
|
|
)
|