Code

Ticket #3143: newforms-timefield.diff

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

new field and tests

Line 
1Index: django/newforms/fields.py
2===================================================================
3--- django/newforms/fields.py   (revision 4201)
4+++ django/newforms/fields.py   (working copy)
5@@ -12,6 +12,7 @@
6 __all__ = (
7     'Field', 'CharField', 'IntegerField',
8     'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
9+    'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
10     'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
11     'RegexField', 'EmailField', 'URLField', 'BooleanField',
12     'ChoiceField', 'MultipleChoiceField',
13@@ -134,6 +135,33 @@
14                 continue
15         raise ValidationError(gettext(u'Enter a valid date.'))
16 
17+DEFAULT_TIME_INPUT_FORMATS = (
18+    '%H:%M:%S',     # '14:30:59'
19+    '%H:%M',        # '14:30'
20+)
21+
22+class TimeField(Field):
23+    def __init__(self, input_formats=None, required=True, widget=None, label=None):
24+        Field.__init__(self, required, widget, label)
25+        self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
26+
27+    def clean(self, value):
28+        """
29+        Validates that the input can be converted to a time. Returns a
30+        Python datetime.time object.
31+        """
32+        Field.clean(self, value)
33+        if value in EMPTY_VALUES:
34+            return None
35+        if isinstance(value, datetime.time):
36+            return value
37+        for format in self.input_formats:
38+            try:
39+                return datetime.time(*time.strptime(value, format)[3:6])
40+            except ValueError:
41+                continue
42+        raise ValidationError(gettext(u'Enter a valid time.'))
43+
44 DEFAULT_DATETIME_INPUT_FORMATS = (
45     '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
46     '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
47Index: tests/regressiontests/forms/tests.py
48===================================================================
49--- tests/regressiontests/forms/tests.py        (revision 4201)
50+++ tests/regressiontests/forms/tests.py        (working copy)
51@@ -834,6 +834,45 @@
52 ...
53 ValidationError: [u'Enter a valid date.']
54 
55+# TimeField ###################################################################
56+
57+>>> import datetime
58+>>> f = TimeField()
59+>>> f.clean(datetime.time(14, 25))
60+datetime.time(14, 25)
61+>>> f.clean(datetime.time(14, 25, 59))
62+datetime.time(14, 25, 59)
63+>>> f.clean('14:25')
64+datetime.time(14, 25)
65+>>> f.clean('14:25:59')
66+datetime.time(14, 25, 59)
67+>>> f.clean('hello')
68+Traceback (most recent call last):
69+...
70+ValidationError: [u'Enter a valid time.']
71+>>> f.clean('1:24 p.m.')
72+Traceback (most recent call last):
73+...
74+ValidationError: [u'Enter a valid time.']
75+
76+TimeField accepts an optional input_formats parameter:
77+>>> f = TimeField(input_formats=['%I:%M %p'])
78+>>> f.clean(datetime.time(14, 25))
79+datetime.time(14, 25)
80+>>> f.clean(datetime.time(14, 25, 59))
81+datetime.time(14, 25, 59)
82+>>> f.clean('4:25 AM')
83+datetime.time(4, 25)
84+>>> f.clean('4:25 PM')
85+datetime.time(16, 25)
86+
87+The input_formats parameter overrides all default input formats,
88+so the default formats won't work unless you specify them:
89+>>> f.clean('14:30:45')
90+Traceback (most recent call last):
91+...
92+ValidationError: [u'Enter a valid time.']
93+
94 # DateTimeField ###############################################################
95 
96 >>> import datetime