forms.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from datetime import datetime, timedelta
  2. from mptt.forms import * # noqa
  3. from django.forms import * # noqa
  4. from django.utils import timezone
  5. from django.utils.encoding import force_text
  6. from django.utils.translation import ugettext_lazy as _
  7. from .utils import parse_iso8601_string
  8. class YesNoSwitchBase(TypedChoiceField):
  9. def prepare_value(self, value):
  10. """normalize bools to binary 1/0 so field works on them too"""
  11. if value in (True, 'True', 'true', 1, '1'):
  12. return 1
  13. else:
  14. return 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. class IsoDateTimeField(DateTimeField):
  26. input_formats = ['iso8601']
  27. def prepare_value(self, value):
  28. try:
  29. return value.isoformat()
  30. except AttributeError:
  31. return value
  32. def to_python(self, value):
  33. """
  34. Validates that the input can be converted to a datetime. Returns a
  35. Python datetime.datetime object.
  36. """
  37. if value in self.empty_values:
  38. return None
  39. try:
  40. return parse_iso8601_string(value)
  41. except ValueError:
  42. raise ValidationError(self.error_messages['invalid'], code='invalid')