summaryrefslogtreecommitdiff
path: root/django/newforms/fields.py
diff options
context:
space:
mode:
authorAdrian Holovaty <adrian@holovaty.com>2006-12-14 20:35:32 +0000
committerAdrian Holovaty <adrian@holovaty.com>2006-12-14 20:35:32 +0000
commitfc11b97e97517fb70d36afd221cfaf702b4664e0 (patch)
treec9d3f8f04c28e839e1622b94aedffabd44c6001e /django/newforms/fields.py
parentad7d92ddf9817ffce326320b3b12f6a135d3ff1e (diff)
Fixed #3143 -- Added TimeField to newforms. Thanks, jkocherhans
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4202 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/newforms/fields.py')
-rw-r--r--django/newforms/fields.py28
1 files changed, 28 insertions, 0 deletions
diff --git a/django/newforms/fields.py b/django/newforms/fields.py
index ce92886371..24849bdbcf 100644
--- a/django/newforms/fields.py
+++ b/django/newforms/fields.py
@@ -12,6 +12,7 @@ import time
__all__ = (
'Field', 'CharField', 'IntegerField',
'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
+ 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
'RegexField', 'EmailField', 'URLField', 'BooleanField',
'ChoiceField', 'MultipleChoiceField',
@@ -134,6 +135,33 @@ class DateField(Field):
continue
raise ValidationError(gettext(u'Enter a valid date.'))
+DEFAULT_TIME_INPUT_FORMATS = (
+ '%H:%M:%S', # '14:30:59'
+ '%H:%M', # '14:30'
+)
+
+class TimeField(Field):
+ def __init__(self, input_formats=None, required=True, widget=None, label=None):
+ Field.__init__(self, required, widget, label)
+ self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
+
+ def clean(self, value):
+ """
+ Validates that the input can be converted to a time. Returns a Python
+ datetime.time object.
+ """
+ Field.clean(self, value)
+ if value in EMPTY_VALUES:
+ return None
+ if isinstance(value, datetime.time):
+ return value
+ for format in self.input_formats:
+ try:
+ return datetime.time(*time.strptime(value, format)[3:6])
+ except ValueError:
+ continue
+ raise ValidationError(gettext(u'Enter a valid time.'))
+
DEFAULT_DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'