Ticket #12467: 12467.3.diff

File 12467.3.diff, 6.7 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..f817289 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 has the correct format (YYYY-MM-DD) "
     603                          u"but is an invalid date."),
    602604    }
    603605    def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
    604606        self.auto_now, self.auto_now_add = auto_now, auto_now_add
    class DateField(Field):  
    620622            return value
    621623
    622624        if not ansi_date_re.search(value):
    623             raise exceptions.ValidationError(self.error_messages['invalid'])
     625            msg = self.error_messages['invalid'] % str(value)
     626            raise exceptions.ValidationError(msg)
    624627        # Now that we have the date string in YYYY-MM-DD format, check to make
    625628        # sure it's a valid date.
    626629        # We could use time.strptime here and catch errors, but datetime.date
    class DateField(Field):  
    629632        try:
    630633            return datetime.date(year, month, day)
    631634        except ValueError, e:
    632             msg = self.error_messages['invalid_date'] % _(str(e))
     635            msg = self.error_messages['invalid_date'] % str(value)
    633636            raise exceptions.ValidationError(msg)
    634637
    635638    def pre_save(self, model_instance, add):
    class DateField(Field):  
    679682
    680683class DateTimeField(DateField):
    681684    default_error_messages = {
    682         'invalid': _(u'Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.'),
     685        'invalid': _(u"'%s' value has an invalid valid date/time format. "
     686                     u"It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."),
    683687    }
    684688    description = _("Date (with time)")
    685689
    class DateTimeField(DateField):  
    702706                value, usecs = value.split('.')
    703707                usecs = int(usecs)
    704708            except ValueError:
    705                 raise exceptions.ValidationError(self.error_messages['invalid'])
     709                raise exceptions.ValidationError(
     710                    self.error_messages['invalid'] % str(value))
    706711        else:
    707712            usecs = 0
    708713        kwargs = {'microsecond': usecs}
    709714        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)
     715            return datetime.datetime(
     716                *time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6], **kwargs)
    712717
    713718        except ValueError:
    714719            try: # Try without seconds.
    715                 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5],
    716                                         **kwargs)
     720                return datetime.datetime(
     721                    *time.strptime(value, '%Y-%m-%d %H:%M')[:5], **kwargs)
    717722            except ValueError: # Try without hour/minutes/seconds.
    718723                try:
    719                     return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3],
    720                                             **kwargs)
     724                    return datetime.datetime(
     725                        *time.strptime(value, '%Y-%m-%d')[:3], **kwargs)
    721726                except ValueError:
    722                     raise exceptions.ValidationError(self.error_messages['invalid'])
     727                    raise exceptions.ValidationError(
     728                        self.error_messages['invalid'] % str(value))
    723729
    724730    def pre_save(self, model_instance, add):
    725731        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..930ab51 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 has the correct format (YYYY-MM-DD) "
     83                u"but is an invalid date."])
     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 has the correct format (YYYY-MM-DD) "
     91                u"but is an invalid date."])
     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