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