forms.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from django.forms import DateTimeField, RadioSelect, TypedChoiceField, ValidationError
  2. from django.utils.translation import ugettext_lazy as _
  3. from .utils import parse_iso8601_string
  4. class IsoDateTimeField(DateTimeField):
  5. input_formats = ['iso8601']
  6. def prepare_value(self, value):
  7. try:
  8. return value.isoformat()
  9. except AttributeError:
  10. return value
  11. def to_python(self, value):
  12. """
  13. Validates that the input can be converted to a datetime. Returns a
  14. Python datetime.datetime object.
  15. """
  16. if value in self.empty_values:
  17. return None
  18. try:
  19. return parse_iso8601_string(value)
  20. except ValueError:
  21. raise ValidationError(self.error_messages['invalid'], code='invalid')
  22. class YesNoSwitchBase(TypedChoiceField):
  23. def prepare_value(self, value):
  24. """normalize bools to binary 1/0 so field works on them too"""
  25. if value in (True, 'True', 'true', 1, '1'):
  26. return 1
  27. else:
  28. return 0
  29. def clean(self, value):
  30. return self.prepare_value(value)
  31. def YesNoSwitch(**kwargs):
  32. yes_label = kwargs.pop('yes_label', _("Yes"))
  33. no_label = kwargs.pop('no_label', _("No"))
  34. return YesNoSwitchBase(
  35. coerce=int,
  36. choices=((1, yes_label),
  37. (0, no_label)),
  38. widget=RadioSelect(attrs={'class': 'yesno-switch'}),
  39. **kwargs
  40. )