forms.py 1.4 KB

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