From ae581816befd992b9e7e667d124f427d849bcfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Honza=20Kr=C3=A1l?= Date: Thu, 18 Jun 2009 00:31:57 +0000 Subject: [PATCH] [soc2009/model-validation] Added code param to ValidationError and use it to override validator's messages git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@11035 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/exceptions.py | 5 ++--- django/core/validators.py | 2 +- django/forms/fields.py | 5 ++++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/django/core/exceptions.py b/django/core/exceptions.py index c0bcbae3ab..e1e6da268a 100644 --- a/django/core/exceptions.py +++ b/django/core/exceptions.py @@ -35,7 +35,7 @@ class FieldError(Exception): NON_FIELD_ERRORS = '__all__' class ValidationError(Exception): """An error while validating data.""" - def __init__(self, message): + def __init__(self, message, code=None): import operator from django.utils.encoding import force_unicode """ @@ -49,11 +49,10 @@ class ValidationError(Exception): if isinstance(message, list): self.messages = [force_unicode(msg) for msg in message] else: + self.code = code message = force_unicode(message) self.messages = [message] - - def __str__(self): # This is needed because, without a __str__(), printing an exception # instance would result in this: diff --git a/django/core/validators.py b/django/core/validators.py index d06e49cb25..aeba5cd835 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -20,7 +20,7 @@ email_re = re.compile( def validate_email(value): if not email_re.search(smart_unicode(value)): - raise ValidationError(_(u'Enter a valid e-mail address.')) + raise ValidationError(_(u'Enter a valid e-mail address.'), code='invalid') class ComplexValidator(object): def get_value(self, name, all_values, obj): diff --git a/django/forms/fields.py b/django/forms/fields.py index 882887f3e0..ee0b387b95 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -131,7 +131,10 @@ class Field(object): try: v(value) except ValidationError, e: - errors.extend(e.messages) + if hasattr(e, 'code'): + errors.append(self.error_messages.get(e.code, e.messages[0])) + else: + errors.extend(e.messages) if errors: raise ValidationError(errors)