From 55e23d5efaa11b7385c9c0d117378b07cdeb7341 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Honza=20Kr=C3=A1l?= Date: Mon, 1 Jun 2009 15:38:11 +0000 Subject: [PATCH] [soc2009/model-validation] Moved ValidationError to django.core.exceptions and removed ErrorList from within the Error git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@10867 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/localflavor/au/forms.py | 2 +- django/contrib/localflavor/ca/forms.py | 2 +- django/core/exceptions.py | 19 ++++++++++++++++++- django/forms/__init__.py | 2 +- django/forms/fields.py | 17 ++++++----------- django/forms/forms.py | 7 ++++--- django/forms/formsets.py | 3 ++- django/forms/models.py | 3 ++- django/forms/util.py | 20 +------------------- tests/regressiontests/forms/util.py | 17 +++++++++-------- 10 files changed, 45 insertions(+), 47 deletions(-) diff --git a/django/contrib/localflavor/au/forms.py b/django/contrib/localflavor/au/forms.py index afc3a0cc4c..4e8a204283 100644 --- a/django/contrib/localflavor/au/forms.py +++ b/django/contrib/localflavor/au/forms.py @@ -4,7 +4,7 @@ Australian-specific Form helpers from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES -from django.forms.util import smart_unicode +from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re diff --git a/django/contrib/localflavor/ca/forms.py b/django/contrib/localflavor/ca/forms.py index 327d938373..9544268cbe 100644 --- a/django/contrib/localflavor/ca/forms.py +++ b/django/contrib/localflavor/ca/forms.py @@ -4,7 +4,7 @@ Canada-specific Form helpers from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES -from django.forms.util import smart_unicode +from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re diff --git a/django/core/exceptions.py b/django/core/exceptions.py index 1c21031739..2fe384e6dd 100644 --- a/django/core/exceptions.py +++ b/django/core/exceptions.py @@ -34,4 +34,21 @@ class FieldError(Exception): class ValidationError(Exception): """An error while validating data.""" - pass + def __init__(self, message): + from django.utils.encoding import force_unicode + """ + ValidationError can be passed any object that can be printed (usually + a string) or a list of objects. + """ + if isinstance(message, list): + self.messages = [force_unicode(msg) for msg in message] + else: + 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: + # AttributeError: ValidationError instance has no attribute 'args' + # See http://www.python.org/doc/current/tut/node10.html#handling + return repr(self.messages) diff --git a/django/forms/__init__.py b/django/forms/__init__.py index 0d9c68f9e0..dc8b5212c4 100644 --- a/django/forms/__init__.py +++ b/django/forms/__init__.py @@ -10,7 +10,7 @@ TODO: "This form field requires foo.js" and form.js_includes() """ -from util import ValidationError +from django.core.exceptions import ValidationError from widgets import * from fields import * from forms import * diff --git a/django/forms/fields.py b/django/forms/fields.py index affe3879b9..3e32d8a6f4 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -23,12 +23,14 @@ try: except NameError: from sets import Set as set -import django.core.exceptions +from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode, smart_str -from util import ErrorList, ValidationError -from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget +from util import ErrorList +from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, \ + FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, \ + DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget from django.core.files.uploadedfile import SimpleUploadedFile as UploadedFile __all__ = ( @@ -683,16 +685,9 @@ class TypedChoiceField(ChoiceField): value = super(TypedChoiceField, self).clean(value) if value == self.empty_value or value in EMPTY_VALUES: return self.empty_value - - # Hack alert: This field is purpose-made to use with Field.to_python as - # a coercion function so that ModelForms with choices work. However, - # Django's Field.to_python raises - # django.core.exceptions.ValidationError, which is a *different* - # exception than django.forms.util.ValidationError. So we need to catch - # both. try: value = self.coerce(value) - except (ValueError, TypeError, django.core.exceptions.ValidationError): + except (ValueError, TypeError, ValidationError): raise ValidationError(self.error_messages['invalid_choice'] % {'value': value}) return value diff --git a/django/forms/forms.py b/django/forms/forms.py index 1b9faa7e4d..6b6f1c5971 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -4,6 +4,7 @@ Form classes from copy import deepcopy +from django.core.exceptions import ValidationError from django.utils.datastructures import SortedDict from django.utils.html import conditional_escape from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode @@ -11,7 +12,7 @@ from django.utils.safestring import mark_safe from fields import Field, FileField from widgets import Media, media_property, TextInput, Textarea -from util import flatatt, ErrorDict, ErrorList, ValidationError +from util import flatatt, ErrorDict, ErrorList __all__ = ('BaseForm', 'Form') @@ -243,13 +244,13 @@ class BaseForm(StrAndUnicode): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError, e: - self._errors[name] = e.messages + self._errors[name] = self.error_class(e.messages) if name in self.cleaned_data: del self.cleaned_data[name] try: self.cleaned_data = self.clean() except ValidationError, e: - self._errors[NON_FIELD_ERRORS] = e.messages + self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages) if self._errors: delattr(self, 'cleaned_data') diff --git a/django/forms/formsets.py b/django/forms/formsets.py index bb8e3107e1..d5101c762e 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -1,10 +1,11 @@ from forms import Form +from django.core.exceptions import ValidationError from django.utils.encoding import StrAndUnicode from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from fields import IntegerField, BooleanField from widgets import Media, HiddenInput -from util import ErrorList, ErrorDict, ValidationError +from util import ErrorList __all__ = ('BaseFormSet', 'all_valid') diff --git a/django/forms/models.py b/django/forms/models.py index a0b217860d..d5d5999c76 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -8,7 +8,8 @@ from django.utils.datastructures import SortedDict from django.utils.text import get_text_list, capfirst from django.utils.translation import ugettext_lazy as _, ugettext -from util import ValidationError, ErrorList +from django.core.exceptions import ValidationError +from util import ErrorList from forms import BaseForm, get_declared_fields, NON_FIELD_ERRORS from fields import Field, ChoiceField, IntegerField, EMPTY_VALUES from widgets import Select, SelectMultiple, HiddenInput, MultipleHiddenInput diff --git a/django/forms/util.py b/django/forms/util.py index b9b88a61e6..8cd1f10f43 100644 --- a/django/forms/util.py +++ b/django/forms/util.py @@ -1,5 +1,5 @@ from django.utils.html import conditional_escape -from django.utils.encoding import smart_unicode, StrAndUnicode, force_unicode +from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.safestring import mark_safe def flatatt(attrs): @@ -48,21 +48,3 @@ class ErrorList(list, StrAndUnicode): def __repr__(self): return repr([force_unicode(e) for e in self]) -class ValidationError(Exception): - def __init__(self, message): - """ - ValidationError can be passed any object that can be printed (usually - a string) or a list of objects. - """ - if isinstance(message, list): - self.messages = ErrorList([smart_unicode(msg) for msg in message]) - else: - message = smart_unicode(message) - self.messages = ErrorList([message]) - - def __str__(self): - # This is needed because, without a __str__(), printing an exception - # instance would result in this: - # AttributeError: ValidationError instance has no attribute 'args' - # See http://www.python.org/doc/current/tut/node10.html#handling - return repr(self.messages) diff --git a/tests/regressiontests/forms/util.py b/tests/regressiontests/forms/util.py index 845ddeaadb..f365c8c1ae 100644 --- a/tests/regressiontests/forms/util.py +++ b/tests/regressiontests/forms/util.py @@ -5,6 +5,7 @@ Tests for forms/util.py module. tests = r""" >>> from django.forms.util import * +>>> from django.core.exceptions import ValidationError >>> from django.utils.translation import ugettext_lazy ########### @@ -24,36 +25,36 @@ u'' ################### # Can take a string. ->>> print ValidationError("There was an error.").messages +>>> print ErrorList(ValidationError("There was an error.").messages) # Can take a unicode string. ->>> print ValidationError(u"Not \u03C0.").messages +>>> print ErrorList(ValidationError(u"Not \u03C0.").messages) # Can take a lazy string. ->>> print ValidationError(ugettext_lazy("Error.")).messages +>>> print ErrorList(ValidationError(ugettext_lazy("Error.")).messages) # Can take a list. ->>> print ValidationError(["Error one.", "Error two."]).messages +>>> print ErrorList(ValidationError(["Error one.", "Error two."]).messages) # Can take a mixture in a list. ->>> print ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages +>>> print ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages) >>> class VeryBadError: ... def __unicode__(self): return u"A very bad error." # Can take a non-string. ->>> print ValidationError(VeryBadError()).messages +>>> print ErrorList(ValidationError(VeryBadError()).messages) # Escapes non-safe input but not input marked safe. >>> example = 'Example of link: example' ->>> print ValidationError(example).messages +>>> print ErrorList([example]) ->>> print ValidationError(mark_safe(example)).messages +>>> print ErrorList([mark_safe(example)]) """