Ticket #3143: newforms-timefield.diff

File newforms-timefield.diff, 3.2 KB (added by jkocherhans, 9 years ago)

new field and tests

  • django/newforms/fields.py

     
    1212__all__ = (
    1313    'Field', 'CharField', 'IntegerField',
    1414    'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
     15    'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
    1516    'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
    1617    'RegexField', 'EmailField', 'URLField', 'BooleanField',
    1718    'ChoiceField', 'MultipleChoiceField',
     
    134135                continue
    135136        raise ValidationError(gettext(u'Enter a valid date.'))
    136137
     138DEFAULT_TIME_INPUT_FORMATS = (
     139    '%H:%M:%S',     # '14:30:59'
     140    '%H:%M',        # '14:30'
     141)
     142
     143class TimeField(Field):
     144    def __init__(self, input_formats=None, required=True, widget=None, label=None):
     145        Field.__init__(self, required, widget, label)
     146        self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
     147
     148    def clean(self, value):
     149        """
     150        Validates that the input can be converted to a time. Returns a
     151        Python datetime.time object.
     152        """
     153        Field.clean(self, value)
     154        if value in EMPTY_VALUES:
     155            return None
     156        if isinstance(value, datetime.time):
     157            return value
     158        for format in self.input_formats:
     159            try:
     160                return datetime.time(*time.strptime(value, format)[3:6])
     161            except ValueError:
     162                continue
     163        raise ValidationError(gettext(u'Enter a valid time.'))
     164
    137165DEFAULT_DATETIME_INPUT_FORMATS = (
    138166    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    139167    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
  • tests/regressiontests/forms/tests.py

     
    834834...
    835835ValidationError: [u'Enter a valid date.']
    836836
     837# TimeField ###################################################################
     838
     839>>> import datetime
     840>>> f = TimeField()
     841>>> f.clean(datetime.time(14, 25))
     842datetime.time(14, 25)
     843>>> f.clean(datetime.time(14, 25, 59))
     844datetime.time(14, 25, 59)
     845>>> f.clean('14:25')
     846datetime.time(14, 25)
     847>>> f.clean('14:25:59')
     848datetime.time(14, 25, 59)
     849>>> f.clean('hello')
     850Traceback (most recent call last):
     851...
     852ValidationError: [u'Enter a valid time.']
     853>>> f.clean('1:24 p.m.')
     854Traceback (most recent call last):
     855...
     856ValidationError: [u'Enter a valid time.']
     857
     858TimeField accepts an optional input_formats parameter:
     859>>> f = TimeField(input_formats=['%I:%M %p'])
     860>>> f.clean(datetime.time(14, 25))
     861datetime.time(14, 25)
     862>>> f.clean(datetime.time(14, 25, 59))
     863datetime.time(14, 25, 59)
     864>>> f.clean('4:25 AM')
     865datetime.time(4, 25)
     866>>> f.clean('4:25 PM')
     867datetime.time(16, 25)
     868
     869The input_formats parameter overrides all default input formats,
     870so the default formats won't work unless you specify them:
     871>>> f.clean('14:30:45')
     872Traceback (most recent call last):
     873...
     874ValidationError: [u'Enter a valid time.']
     875
    837876# DateTimeField ###############################################################
    838877
    839878>>> import datetime
Back to Top