forms.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django import forms
  2. from core.models import Politician, Party
  3. from core.widgets import ImagePreviewFileInput
  4. class PoliticianForm(forms.ModelForm):
  5. class Meta:
  6. model = Politician
  7. exclude = ['unique_key', 'user']
  8. widgets = {
  9. 'image': ImagePreviewFileInput()
  10. }
  11. def clean_image(self):
  12. image = self.cleaned_data.get('image')
  13. if image:
  14. if image.size > 5*1024*1024:
  15. raise forms.ValidationError('Image file too large ( > 5MB )')
  16. return image
  17. def clean_party_other(self):
  18. data = self.cleaned_data.get('party_other')
  19. if self.cleaned_data.get('party'):
  20. data = None
  21. return data
  22. def __init__(self, *args, **kwargs):
  23. kwargs.setdefault('label_suffix', '')
  24. super(PoliticianForm, self).__init__(*args, **kwargs)
  25. for field_name, field in self.fields.iteritems():
  26. if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select):
  27. field.widget.attrs.update({
  28. 'class': 'form-control'
  29. })
  30. if field_name == 'party':
  31. field.choices = [('', '---------')]
  32. field.choices += [
  33. (p.id, p.name)
  34. for p
  35. in Party.objects.order_by('name')
  36. ]
  37. if isinstance(field.widget, forms.Textarea):
  38. field.widget.attrs.update({
  39. 'class': 'form-control',
  40. 'rows': 2,
  41. })
  42. class PartyPoliticianForm(forms.ModelForm):
  43. class Meta:
  44. model = Politician
  45. fields = ['first_name', 'last_name', 'email', 'state', 'is_member_of_parliament', 'user']
  46. def __init__(self, *args, **kwargs):
  47. kwargs.setdefault('label_suffix', '')
  48. super(PartyPoliticianForm, self).__init__(*args, **kwargs)
  49. for field_name, field in self.fields.iteritems():
  50. if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select):
  51. field.widget.attrs.update({
  52. 'class': 'form-control'
  53. })