forms.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from django.forms import DateTimeField, RadioSelect, TypedChoiceField, ValidationError
  2. from django.utils.translation import ugettext_lazy as _
  3. from misago.core.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=[
  37. (1, yes_label),
  38. (0, no_label),
  39. ],
  40. widget=RadioSelect(attrs={'class': 'yesno-switch'}),
  41. **kwargs
  42. )