PageRenderTime 546ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/source/elections/forms.py

https://github.com/openstate/Wiekiesjij
Python | 267 lines | 229 code | 19 blank | 19 comment | 6 complexity | ea8bd2c8b087733edeca63debd9028c0 MD5 | raw file
  1. from django import forms
  2. from django.forms import widgets
  3. from django.conf import settings
  4. from django.utils.translation import ugettext_lazy as _
  5. from form_utils.forms import BetterForm, BetterModelForm
  6. from utils.widgets import AutoCompleter, ColorPicker, HiddenDateTimePicker, DateTimePicker, ImageWidget
  7. from utils.fields import AddressField, YoutubeURLField
  8. from utils.formutils import TemplateForm
  9. #from utils.validators import
  10. #from utils.fields import ZipCodeField, PhoneField
  11. from elections.models import Candidacy, Council, ElectionEvent, ElectionInstance, ElectionInstanceQuestion, Party
  12. from elections.models import ElectionInstanceParty, ElectionInstanceModule
  13. from utils.fields import DutchMobilePhoneField
  14. from utils.forms import ModelMultiAnswerForm
  15. from questions.models import QuestionSet
  16. from django.template.loader import render_to_string
  17. class CouncilEventMultipleModelChoiceField(forms.ModelMultipleChoiceField):
  18. def __init__(self, *args, **kwargs):
  19. super(self.__class__, self).__init__(*args, **kwargs)
  20. def label_from_instance(self, obj):
  21. return render_to_string('elections/_council_event.html', {'council_event': obj})
  22. class SmsEventForm(BetterForm, TemplateForm):
  23. value = CouncilEventMultipleModelChoiceField(label=_('Selecteer de evenementen waar u een SMS voor wilt ontvangen'), queryset=None, widget=widgets.CheckboxSelectMultiple)
  24. phone_number = DutchMobilePhoneField(label=_('Your mobile phone number'), required=True)
  25. # class Meta:
  26. # fieldsets = (('main', {'fields': ('value',), 'legend': '', 'classes': ('default','party-selection')}),)
  27. #
  28. def __init__(self, queryset=None, empty_label=None, *args, **kwargs):
  29. super(self.__class__, self).__init__(*args, **kwargs)
  30. try:
  31. self.fields['value'].empty_label = empty_label
  32. self.fields['value'].queryset = queryset
  33. except Exception:
  34. raise ModelAnswerFormError('You need to provide a model to the ModelAnswerForm')
  35. class ElectionInstanceSelectPartiesForm(BetterForm, TemplateForm):
  36. '''
  37. Select a list of parties that are in your election from a list of hardcoded partys in the netherlands.
  38. '''
  39. parties = forms.MultipleChoiceField(label=_('Parties'), widget=forms.CheckboxSelectMultiple,
  40. choices=settings.COMMON_PARTIES, required=False)
  41. class Meta:
  42. fields = ('parties',)
  43. class CandidacyForm(BetterModelForm, TemplateForm):
  44. '''
  45. PoliticianProfile admin
  46. '''
  47. class Meta:
  48. model = Candidacy
  49. class InitialCouncilForm(BetterModelForm, TemplateForm):
  50. '''
  51. ChanceryProfile admin
  52. '''
  53. #address = AddressField(_('Address'))
  54. class Meta:
  55. model = Council
  56. fields = ('name', 'house_num', 'street', 'postcode', 'town', 'email', 'phone', 'website' )
  57. '''
  58. def clean_address(self):
  59. """
  60. Puts the subfields of the address multivaluefield into separate fields
  61. """
  62. fields = ['street', 'number', 'postalcode', 'city']
  63. for key in fields:
  64. self.cleaned_data[key] = self.cleaned_data['address'].split(' ')[fields.index(key)]
  65. return self.cleaned_data['address']
  66. '''
  67. class CouncilForm(BetterModelForm, TemplateForm):
  68. '''
  69. ChanceryProfile admin
  70. '''
  71. seats = forms.IntegerField(label=_('Seats'), required=False, help_text=_('Wat is het huidige aantal zetels in uw Tweede Kamer.'))
  72. def __init__(self, *args, **kwargs):
  73. super(CouncilForm, self).__init__(*args, **kwargs)
  74. self.fields['history'].widget = forms.widgets.Textarea()
  75. class Meta:
  76. model = Council
  77. fields = ('seats', 'history', )
  78. class CouncilContactInformationForm(BetterForm, TemplateForm):
  79. '''
  80. Council information form (used in 2. Election overview)
  81. '''
  82. name = forms.CharField(label=_('Name'), help_text=_('Geef hier de naam van uw Tweede Kamer op.).'))
  83. address = AddressField(label=_('Address of the Council'), help_text=_('Vul hier uw contactinformatie in.'))
  84. email = forms.EmailField(label=_('E-Mail'), help_text=_('We gebruiken hier het emailadres van wiekiesjij.nl'))
  85. website = forms.URLField(label=_('Website of the Council'), help_text=_('Vul hier de permanente website van de Tweede Kamer in.'), required=False)
  86. class Meta:
  87. fields = ('name', 'address', 'website',)
  88. class CouncilStylingSetupForm(BetterModelForm, TemplateForm):
  89. '''
  90. Council styling setup form (used in 2. Election overview)
  91. '''
  92. def __init__(self, *args, **kwargs):
  93. super(CouncilStylingSetupForm, self).__init__(*args, **kwargs)
  94. self.fields['background_color'].widget = ColorPicker()
  95. self.fields['foreground_color'].widget = ColorPicker()
  96. self.fields['another_color'].widget = ColorPicker()
  97. class Meta:
  98. model = Council
  99. fields = ('background_color', 'foreground_color', 'another_color',)
  100. class ElectionEventForm(BetterModelForm, TemplateForm):
  101. '''
  102. Contact Profile admin
  103. '''
  104. class Meta:
  105. model = ElectionEvent
  106. class InitialElectionInstanceForm(BetterModelForm, TemplateForm):
  107. '''
  108. ElectionInstance admin
  109. '''
  110. modules = forms.ModelMultipleChoiceField(required=False,
  111. label=_('Which modules do you want to enable for this instance?'),
  112. queryset=ElectionInstanceModule.objects,
  113. widget=forms.widgets.CheckboxSelectMultiple)
  114. name = forms.CharField(help_text=_('Insert the name of the country here.'))
  115. region = forms.CharField(label=_('Region'), widget=AutoCompleter(model=Council, field='region'), help_text=_('Probably the same as the name of your country.'))
  116. level = forms.CharField(label=_('Level'), widget=AutoCompleter(model=Council, field='level'), help_text=_('For example for a national election, the level would be Country.'))
  117. question_set = forms.ModelChoiceField(label=_('Question set'), queryset=QuestionSet.objects.all(), empty_label=_('(None)'), help_text=_('The question set to use for this election instance'))
  118. class Meta:
  119. model = ElectionInstance
  120. fields = ('name', 'region', 'level', 'modules')
  121. class ElectionInstanceForm(BetterModelForm, TemplateForm):
  122. '''
  123. ElectionInstance admin
  124. '''
  125. start_date = forms.DateTimeField(
  126. label=_('When does this election take place?'),
  127. widget=DateTimePicker)
  128. start_date.hidden_widget = HiddenDateTimePicker
  129. website = forms.URLField(label=_('Election Website'), required=False, initial='http://', help_text=_('Als uw Tweede Kamer een speciale promotie website heeft voor deze verkiezing, kunt u de URL hier invullen.'))
  130. num_lists = forms.IntegerField(label=_('Number of parties in this election.'), required=False, help_text=_('How many parties are taking part in this election?'))
  131. class Meta:
  132. model = ElectionInstance
  133. fields = ('start_date', 'website', 'num_lists')
  134. def __init__(self, *args, **kwargs):
  135. if 'instance' in kwargs:
  136. self.instance = kwargs['instance']
  137. self.instance.start_date = self.instance.election_event.default_date
  138. super(ElectionInstanceForm, self).__init__(*args, **kwargs)
  139. if 'instance' in kwargs:
  140. self.fields['start_date'].help_text = _('Vul hier het moment in dat de stembussen sluiten. De datum %(def_date)s is de standaard datum voor %(ev_name)s.') % {
  141. 'def_date': self.instance.election_event.default_date.strftime('%d-%m-%Y'),
  142. 'ev_name': self.instance.election_event.name,
  143. }
  144. def clean_num_lists(self):
  145. """
  146. We have to check if the number is not already exceeded
  147. """
  148. # No checking for unbound form
  149. if not self.instance:
  150. return self.cleaned_data['num_lists']
  151. num_lists = self.cleaned_data['num_lists']
  152. largest_position = 0
  153. for eip in self.instance.election_instance_parties.all():
  154. if eip.position > largest_position:
  155. largest_position = eip.position
  156. if largest_position > num_lists:
  157. raise forms.ValidationError( _('Number needs to be at least %(largest_position)s because there is a party in this position already.') % {'largest_position':largest_position, 'num_lists': num_lists } )
  158. return self.cleaned_data['num_lists']
  159. class EditElectionInstanceForm(BetterModelForm, TemplateForm):
  160. """
  161. EditElectionInstanceForm
  162. """
  163. modules = forms.ModelMultipleChoiceField(required=False,
  164. label=_('Modules'),
  165. queryset=ElectionInstanceModule.objects,
  166. widget=forms.widgets.CheckboxSelectMultiple)
  167. class Meta:
  168. model = ElectionInstance
  169. fields = ('name', 'modules')
  170. class ElectionInstanceQuestionForm(BetterModelForm, TemplateForm):
  171. '''
  172. ElectionInstanceQuestion
  173. '''
  174. class Meta:
  175. model = ElectionInstanceQuestion
  176. class PartyForm(BetterModelForm, TemplateForm):
  177. '''
  178. Party admin
  179. '''
  180. class Meta:
  181. model = Party
  182. class InitialElectionPartyForm(BetterForm, TemplateForm):
  183. name = forms.CharField(label=_('Full party name'), help_text=_('Vul hier de volledige naam van uw partij in (b.v. Volkspartij voor Vrijheid en Democratie).'), max_length=255)
  184. abbreviation = forms.CharField(label=_('Abbreviated Party Name'), help_text=_('Vul hier de afkorting van uw partij in (b.v. VVD).'), required=True, max_length=20)
  185. #list_length = forms.IntegerField(label=_('Number of candidates in this election'), min_value=1, max_value=100, help_text=_('The number of positions available for this election'))
  186. position = forms.IntegerField(widget=forms.widgets.HiddenInput())
  187. class ElectionPartyContactForm(BetterForm, TemplateForm):
  188. name = forms.CharField(label=_('Full party name'), max_length=255, widget=AutoCompleter(model=Party, field='name'), help_text=_('Vul hier de volledige naam van uw partij in (b.v. Volkspartij voor Vrijheid en Democratie).'))
  189. abbreviation = forms.CharField(label=_('Abbreviated party name'), max_length=20 , help_text=_('Vul hier de afkorting van uw partij in (b.v. VVD). (20 tekens)'), required=True)
  190. address = AddressField(label=_('Address'), help_text=_('Vul hier uw contactinformatie in (b.v. adres van campagne team).'))
  191. email = forms.EmailField(label=_('E-mail address'), help_text=_('Vul hier het email adres in waarmee u met Wiekiesjij wenst te corresponderen.'))
  192. telephone = forms.CharField(label=_('Phone number'), help_text=_('Vul hier het telefoonnummer van uw campagneteam in.'))
  193. website = forms.URLField(max_length=255, label=_('Party website'), help_text=_('Vul hier de website van uw partij in.'), required=False)
  194. class ElectionPartyAdditionalForm(BetterForm, TemplateForm):
  195. list_length = forms.IntegerField(label=_('Number of candidates in this election'), min_value=0, help_text=_('Vul hier het aantal kandidaten die uw partij deze verkiezingen representeren in.'), required = False)
  196. slogan = forms.CharField(max_length=255, label=_('Slogan'), help_text=_('Vul hier uw verkiezingsslogan in. (255 tekens) '), required = False)
  197. movie = YoutubeURLField(label=_('Movie'), help_text=_('Link naar YouTube video. LET OP: gebruik de lange versie van de link, die begint met http://www.youtube.com/'), required=False)
  198. logo = forms.ImageField(_('Logo'), widget=ImageWidget())
  199. num_seats = forms.IntegerField(label=_('Current number of seats'), min_value=0, help_text=_('Vul hier het huidige aantal zetels in (vul 0 in als u momenteel geen zetels heeft).'), required = False)
  200. class ElectionPartyDescriptionForm(BetterForm, TemplateForm):
  201. description = forms.CharField(max_length=255, label=_('Short description'), widget = forms.widgets.Textarea(), help_text=_('Vul hier een korte beschrijving over uw partij in. Beantwoord voornamelijk de vraag wie u bent. (255 tekens)'), required = False)
  202. history = forms.CharField(max_length=255, label=_('Short history'), widget = forms.widgets.Textarea(), help_text=_('Vul hier een korte geschiedenis van uw partij in. Beantwoord voornamelijk hoe u bent ontstaan, en waar u in het verleden voor gestreden heeft. (255 tekens)'), required = False)
  203. manifesto_summary = forms.CharField(label=_('Manifesto Summary'), widget=forms.Textarea(), help_text=_('Vul hier een korte beschrijving van uw verkiezingsprogramma in. Beantwoord voornamelijk waar u voor staat.'), required = False)
  204. manifesto = forms.URLField(label=_('Link to the manifesto'), help_text=_('Vul hier een link in naar uw verkiezingsprogramma. Dit mag een website of PDF document zijn. '), required = False)