forms.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from mptt.forms import * # noqa
  2. from django.forms import * # noqa
  3. from django.forms import Form as BaseForm, ModelForm as BaseModelForm
  4. from django.utils.translation import ugettext_lazy as _
  5. TEXT_BASED_FIELDS = (
  6. CharField, EmailField, FilePathField, URLField
  7. )
  8. """
  9. Fields
  10. """
  11. class YesNoSwitchBase(TypedChoiceField):
  12. def prepare_value(self, value):
  13. """normalize bools to binary 1/0 so field works on them too"""
  14. return 1 if value in [True, 'True', 1, '1'] else 0
  15. def clean(self, value):
  16. return self.prepare_value(value)
  17. def YesNoSwitch(**kwargs):
  18. yes_label = kwargs.pop('yes_label', _("Yes"))
  19. no_label = kwargs.pop('no_label', _("No"))
  20. return YesNoSwitchBase(
  21. coerce=int,
  22. choices=((1, yes_label), (0, no_label)),
  23. widget=RadioSelect(attrs={'class': 'yesno-switch'}),
  24. **kwargs)
  25. """
  26. Forms
  27. """
  28. class AutoStripWhitespacesMixin(object):
  29. autostrip_exclude = []
  30. def full_clean(self):
  31. self.data = self.data.copy()
  32. for name, field in self.fields.iteritems():
  33. if (field.__class__ in TEXT_BASED_FIELDS and
  34. not name in self.autostrip_exclude):
  35. try:
  36. self.data[name] = self.data[name].strip()
  37. except KeyError:
  38. pass
  39. return super(AutoStripWhitespacesMixin, self).full_clean()
  40. class Form(AutoStripWhitespacesMixin, BaseForm):
  41. pass
  42. class ModelForm(AutoStripWhitespacesMixin, BaseModelForm):
  43. pass