kadenios/elections/forms.py
2020-12-18 00:19:18 +01:00

31 lines
847 B
Python

from django import forms
from django.forms.models import inlineformset_factory
from .models import Option, Question
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
)