Ticket #3143: newforms-timefield.diff
File newforms-timefield.diff, 3.2 KB (added by , 18 years ago) |
---|
-
django/newforms/fields.py
12 12 __all__ = ( 13 13 'Field', 'CharField', 'IntegerField', 14 14 'DEFAULT_DATE_INPUT_FORMATS', 'DateField', 15 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField', 15 16 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 16 17 'RegexField', 'EmailField', 'URLField', 'BooleanField', 17 18 'ChoiceField', 'MultipleChoiceField', … … 134 135 continue 135 136 raise ValidationError(gettext(u'Enter a valid date.')) 136 137 138 DEFAULT_TIME_INPUT_FORMATS = ( 139 '%H:%M:%S', # '14:30:59' 140 '%H:%M', # '14:30' 141 ) 142 143 class 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 137 165 DEFAULT_DATETIME_INPUT_FORMATS = ( 138 166 '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' 139 167 '%Y-%m-%d %H:%M', # '2006-10-25 14:30' -
tests/regressiontests/forms/tests.py
834 834 ... 835 835 ValidationError: [u'Enter a valid date.'] 836 836 837 # TimeField ################################################################### 838 839 >>> import datetime 840 >>> f = TimeField() 841 >>> f.clean(datetime.time(14, 25)) 842 datetime.time(14, 25) 843 >>> f.clean(datetime.time(14, 25, 59)) 844 datetime.time(14, 25, 59) 845 >>> f.clean('14:25') 846 datetime.time(14, 25) 847 >>> f.clean('14:25:59') 848 datetime.time(14, 25, 59) 849 >>> f.clean('hello') 850 Traceback (most recent call last): 851 ... 852 ValidationError: [u'Enter a valid time.'] 853 >>> f.clean('1:24 p.m.') 854 Traceback (most recent call last): 855 ... 856 ValidationError: [u'Enter a valid time.'] 857 858 TimeField accepts an optional input_formats parameter: 859 >>> f = TimeField(input_formats=['%I:%M %p']) 860 >>> f.clean(datetime.time(14, 25)) 861 datetime.time(14, 25) 862 >>> f.clean(datetime.time(14, 25, 59)) 863 datetime.time(14, 25, 59) 864 >>> f.clean('4:25 AM') 865 datetime.time(4, 25) 866 >>> f.clean('4:25 PM') 867 datetime.time(16, 25) 868 869 The input_formats parameter overrides all default input formats, 870 so the default formats won't work unless you specify them: 871 >>> f.clean('14:30:45') 872 Traceback (most recent call last): 873 ... 874 ValidationError: [u'Enter a valid time.'] 875 837 876 # DateTimeField ############################################################### 838 877 839 878 >>> import datetime