diff --git a/django/newforms/fields.py b/django/newforms/fields.py index 471318e95f..167281a061 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -516,11 +516,13 @@ class MultiValueField(Field): """ clean_data = [] errors = ErrorList() - if self.required and not value: - raise ValidationError(gettext(u'This field is required.')) - elif not self.required and not value: - return self.compress([]) - if not isinstance(value, (list, tuple)): + if not value or isinstance(value, (list, tuple)): + if not value or not [v for v in value if v not in EMPTY_VALUES]: + if self.required: + raise ValidationError(gettext(u'This field is required.')) + else: + return self.compress([]) + else: raise ValidationError(gettext(u'Enter a list of values.')) for i, field in enumerate(self.fields): try: @@ -558,5 +560,11 @@ class SplitDateTimeField(MultiValueField): def compress(self, data_list): if data_list: + # Raise a validation error if time or date is empty + # (possible if SplitDateTimeField has required=False). + if data_list[0] in EMPTY_VALUES: + raise ValidationError(gettext(u'Enter a valid date.')) + if data_list[1] in EMPTY_VALUES: + raise ValidationError(gettext(u'Enter a valid time.')) return datetime.datetime.combine(*data_list) return None diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/tests.py index 4844267b43..d487ab9e8e 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/tests.py @@ -1859,8 +1859,12 @@ ValidationError: [u'Enter a valid date.'] >>> f = SplitDateTimeField(required=False) >>> f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) datetime.datetime(2006, 1, 10, 7, 30) +>>> f.clean(['2006-01-10', '07:30']) +datetime.datetime(2006, 1, 10, 7, 30) >>> f.clean(None) >>> f.clean('') +>>> f.clean(['']) +>>> f.clean(['', '']) >>> f.clean('hello') Traceback (most recent call last): ... @@ -1877,6 +1881,18 @@ ValidationError: [u'Enter a valid time.'] Traceback (most recent call last): ... ValidationError: [u'Enter a valid date.'] +>>> f.clean(['2006-01-10', '']) +Traceback (most recent call last): +... +ValidationError: [u'Enter a valid time.'] +>>> f.clean(['2006-01-10']) +Traceback (most recent call last): +... +ValidationError: [u'Enter a valid time.'] +>>> f.clean(['', '07:30']) +Traceback (most recent call last): +... +ValidationError: [u'Enter a valid date.'] ######### # Forms #