Ticket #12467: 12467.2.diff

File 12467.2.diff, 6.6 KB (added by Julien Phalip, 13 years ago)
  • django/db/models/fields/__init__.py

    diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
    index 0c68428..7b24ed5 100644
    a b class DateField(Field):  
    597597
    598598    empty_strings_allowed = False
    599599    default_error_messages = {
    600         'invalid': _('Enter a valid date in YYYY-MM-DD format.'),
    601         'invalid_date': _('Invalid date: %s'),
     600        'invalid': _(u"'%s' value has an invalid date format. It must be "
     601                     u"in YYYY-MM-DD format."),
     602        'invalid_date': _(u"'%s' value is an invalid date: %s"),
    602603    }
    603604    def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
    604605        self.auto_now, self.auto_now_add = auto_now, auto_now_add
    class DateField(Field):  
    620621            return value
    621622
    622623        if not ansi_date_re.search(value):
    623             raise exceptions.ValidationError(self.error_messages['invalid'])
     624            msg = self.error_messages['invalid'] % str(value)
     625            raise exceptions.ValidationError(msg)
    624626        # Now that we have the date string in YYYY-MM-DD format, check to make
    625627        # sure it's a valid date.
    626628        # We could use time.strptime here and catch errors, but datetime.date
    class DateField(Field):  
    629631        try:
    630632            return datetime.date(year, month, day)
    631633        except ValueError, e:
    632             msg = self.error_messages['invalid_date'] % _(str(e))
     634            msg = self.error_messages['invalid_date'] % (str(value), _(str(e)))
    633635            raise exceptions.ValidationError(msg)
    634636
    635637    def pre_save(self, model_instance, add):
    class DateField(Field):  
    679681
    680682class DateTimeField(DateField):
    681683    default_error_messages = {
    682         'invalid': _(u'Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.'),
     684        'invalid': _(u"'%s' value has an invalid valid date/time format. "
     685                     u"It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."),
    683686    }
    684687    description = _("Date (with time)")
    685688
    class DateTimeField(DateField):  
    702705                value, usecs = value.split('.')
    703706                usecs = int(usecs)
    704707            except ValueError:
    705                 raise exceptions.ValidationError(self.error_messages['invalid'])
     708                raise exceptions.ValidationError(
     709                    self.error_messages['invalid'] % str(value))
    706710        else:
    707711            usecs = 0
    708712        kwargs = {'microsecond': usecs}
    709713        try: # Seconds are optional, so try converting seconds first.
    710             return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6],
    711                                     **kwargs)
     714            return datetime.datetime(
     715                *time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6], **kwargs)
    712716
    713717        except ValueError:
    714718            try: # Try without seconds.
    715                 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5],
    716                                         **kwargs)
     719                return datetime.datetime(
     720                    *time.strptime(value, '%Y-%m-%d %H:%M')[:5], **kwargs)
    717721            except ValueError: # Try without hour/minutes/seconds.
    718722                try:
    719                     return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3],
    720                                             **kwargs)
     723                    return datetime.datetime(
     724                        *time.strptime(value, '%Y-%m-%d')[:3], **kwargs)
    721725                except ValueError:
    722                     raise exceptions.ValidationError(self.error_messages['invalid'])
     726                    raise exceptions.ValidationError(
     727                        self.error_messages['invalid'] % str(value))
    723728
    724729    def pre_save(self, model_instance, add):
    725730        if self.auto_now or (self.auto_now_add and add):
  • tests/modeltests/validation/test_error_messages.py

    diff --git a/tests/modeltests/validation/test_error_messages.py b/tests/modeltests/validation/test_error_messages.py
    index 45d0327..a4fb8e0 100644
    a b class ValidationMessagesTest(TestCase):  
    5555        except ValidationError, e:
    5656            self.assertEqual(e.messages,
    5757                        [u"'foo' value must be either None, True or False."])
     58
     59    def test_date_field_raises_error_message(self):
     60        f = models.DateField()
     61        self.assertRaises(ValidationError, f.clean, 'foo', None)
     62        try:
     63            f.clean('foo', None)
     64        except ValidationError, e:
     65            self.assertEqual(e.messages, [
     66                u"'foo' value has an invalid date format. "
     67                u"It must be in YYYY-MM-DD format."])
     68
     69        self.assertRaises(ValidationError, f.clean, 'aaaa-10-10', None)
     70        try:
     71            f.clean('aaaa-10-10', None)
     72        except ValidationError, e:
     73            self.assertEqual(e.messages, [
     74                u"'aaaa-10-10' value has an invalid date format. "
     75                u"It must be in YYYY-MM-DD format."])
     76
     77        self.assertRaises(ValidationError, f.clean, '2011-13-10', None)
     78        try:
     79            f.clean('2011-13-10', None)
     80        except ValidationError, e:
     81            self.assertEqual(e.messages, [
     82                u"'2011-13-10' value is an invalid date: "
     83                u"month must be in 1..12"])
     84
     85        self.assertRaises(ValidationError, f.clean, '2011-10-32', None)
     86        try:
     87            f.clean('2011-10-32', None)
     88        except ValidationError, e:
     89            self.assertEqual(e.messages, [
     90                u"'2011-10-32' value is an invalid date: "
     91                u"day is out of range for month"])
     92
     93    def test_datetime_field_raises_error_message(self):
     94        f = models.DateTimeField()
     95        self.assertRaises(ValidationError, f.clean, 'foo', None)
     96        try:
     97            f.clean('foo', None)
     98        except ValidationError, e:
     99            self.assertEqual(e.messages, [
     100                u"'foo' value has an invalid valid date/time format. "
     101                u"It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."])
     102 No newline at end of file
  • tests/modeltests/validation/tests.py

    diff --git a/tests/modeltests/validation/tests.py b/tests/modeltests/validation/tests.py
    index e6e5d97..5b20df4 100644
    a b from modeltests.validation.validators import TestModelsWithValidators  
    1212from modeltests.validation.test_unique import (GetUniqueCheckTests,
    1313    PerformUniqueChecksTest)
    1414from modeltests.validation.test_custom_messages import CustomMessagesTest
    15 
     15from modeltests.validation.test_error_messages import ValidationMessagesTest
    1616
    1717class BaseModelValidationTests(ValidationTestCase):
    1818
Back to Top