Skip to content

Commit

Permalink
Fixed #3457 -- Allow overridding of error messages for newforms Fields.
Browse files Browse the repository at this point in the history
git-svn-id: http://code.djangoproject.com/svn/django/trunk@6625 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
gdub committed Oct 28, 2007
1 parent ee49e93 commit 26ea06b
Show file tree
Hide file tree
Showing 7 changed files with 534 additions and 55 deletions.
202 changes: 154 additions & 48 deletions django/newforms/fields.py

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions django/newforms/util.py
Expand Up @@ -42,13 +42,18 @@ def as_text(self):
if not self: return u'' if not self: return u''
return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) return u'\n'.join([u'* %s' % force_unicode(e) for e in self])


def __repr__(self):
return repr([force_unicode(e) for e in self])

class ValidationError(Exception): class ValidationError(Exception):
def __init__(self, message): def __init__(self, message):
"ValidationError can be passed a string or a list." """
ValidationError can be passed any object that can be printed (usually
a string) or a list of objects.
"""
if isinstance(message, list): if isinstance(message, list):
self.messages = ErrorList([smart_unicode(msg) for msg in message]) self.messages = ErrorList([smart_unicode(msg) for msg in message])
else: else:
assert isinstance(message, (basestring, Promise)), ("%s should be a basestring or lazy translation" % repr(message))
message = smart_unicode(message) message = smart_unicode(message)
self.messages = ErrorList([message]) self.messages = ErrorList([message])


Expand All @@ -58,4 +63,3 @@ def __str__(self):
# AttributeError: ValidationError instance has no attribute 'args' # AttributeError: ValidationError instance has no attribute 'args'
# See http://www.python.org/doc/current/tut/node10.html#handling # See http://www.python.org/doc/current/tut/node10.html#handling
return repr(self.messages) return repr(self.messages)

2 changes: 1 addition & 1 deletion django/test/testcases.py
Expand Up @@ -146,7 +146,7 @@ def assertFormError(self, response, form, field, errors):
" context %d does not contain the" " context %d does not contain the"
" error '%s' (actual errors: %s)" % " error '%s' (actual errors: %s)" %
(field, form, i, err, (field, form, i, err,
list(field_errors))) repr(field_errors)))
elif field in context[form].fields: elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d" self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i)) " contains no errors" % (field, form, i))
Expand Down
51 changes: 48 additions & 3 deletions docs/newforms.txt
Expand Up @@ -1078,6 +1078,30 @@ fields. We've specified ``auto_id=False`` to simplify the output::
<p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p> <p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p>
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p> <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>


``error_messages``
~~~~~~~~~~~~~~~~~~

**New in Django development version**

The ``error_messages`` argument lets you override the default messages which the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override. For example::

>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
...
ValidationError: [u'This field is required.']

>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
...
ValidationError: [u'Please enter your name']

In the `built-in Field classes`_ section below, each Field defines the error
message keys it uses.

Dynamic initial values Dynamic initial values
---------------------- ----------------------


Expand Down Expand Up @@ -1143,6 +1167,7 @@ For each field, we describe the default widget used if you don't specify
* Normalizes to: A Python ``True`` or ``False`` value. * Normalizes to: A Python ``True`` or ``False`` value.
* Validates that the check box is checked (i.e. the value is ``True``) if * Validates that the check box is checked (i.e. the value is ``True``) if
the field has ``required=True``. the field has ``required=True``.
* Error message keys: ``required``


**New in Django development version:** The empty value for a ``CheckboxInput`` **New in Django development version:** The empty value for a ``CheckboxInput``
(and hence the standard ``BooleanField``) has changed to return ``False`` (and hence the standard ``BooleanField``) has changed to return ``False``
Expand All @@ -1162,6 +1187,7 @@ instead of ``None`` in the development version.
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates ``max_length`` or ``min_length``, if they are provided. * Validates ``max_length`` or ``min_length``, if they are provided.
Otherwise, all inputs are valid. Otherwise, all inputs are valid.
* Error message keys: ``required``, ``max_length``, ``min_length``


Has two optional arguments for validation, ``max_length`` and ``min_length``. Has two optional arguments for validation, ``max_length`` and ``min_length``.
If provided, these arguments ensure that the string is at most or at least the If provided, these arguments ensure that the string is at most or at least the
Expand All @@ -1174,6 +1200,7 @@ given length.
* Empty value: ``''`` (an empty string) * Empty value: ``''`` (an empty string)
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates that the given value exists in the list of choices. * Validates that the given value exists in the list of choices.
* Error message keys: ``required``, ``invalid_choice``


Takes one extra argument, ``choices``, which is an iterable (e.g., a list or Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
tuple) of 2-tuples to use as choices for this field. tuple) of 2-tuples to use as choices for this field.
Expand All @@ -1186,6 +1213,7 @@ tuple) of 2-tuples to use as choices for this field.
* Normalizes to: A Python ``datetime.date`` object. * Normalizes to: A Python ``datetime.date`` object.
* Validates that the given value is either a ``datetime.date``, * Validates that the given value is either a ``datetime.date``,
``datetime.datetime`` or string formatted in a particular date format. ``datetime.datetime`` or string formatted in a particular date format.
* Error message keys: ``required``, ``invalid``


Takes one optional argument, ``input_formats``, which is a list of formats used Takes one optional argument, ``input_formats``, which is a list of formats used
to attempt to convert a string to a valid ``datetime.date`` object. to attempt to convert a string to a valid ``datetime.date`` object.
Expand All @@ -1206,6 +1234,7 @@ If no ``input_formats`` argument is provided, the default input formats are::
* Normalizes to: A Python ``datetime.datetime`` object. * Normalizes to: A Python ``datetime.datetime`` object.
* Validates that the given value is either a ``datetime.datetime``, * Validates that the given value is either a ``datetime.datetime``,
``datetime.date`` or string formatted in a particular datetime format. ``datetime.date`` or string formatted in a particular datetime format.
* Error message keys: ``required``, ``invalid``


Takes one optional argument, ``input_formats``, which is a list of formats used Takes one optional argument, ``input_formats``, which is a list of formats used
to attempt to convert a string to a valid ``datetime.datetime`` object. to attempt to convert a string to a valid ``datetime.datetime`` object.
Expand Down Expand Up @@ -1235,6 +1264,9 @@ If no ``input_formats`` argument is provided, the default input formats are::
* Normalizes to: A Python ``decimal``. * Normalizes to: A Python ``decimal``.
* Validates that the given value is a decimal. Leading and trailing * Validates that the given value is a decimal. Leading and trailing
whitespace is ignored. whitespace is ignored.
* Error message keys: ``required``, ``invalid``, ``max_value``,
``min_value``, ``max_digits``, ``max_decimal_places``,
``max_whole_digits``


Takes four optional arguments: ``max_value``, ``min_value``, ``max_digits``, Takes four optional arguments: ``max_value``, ``min_value``, ``max_digits``,
and ``decimal_places``. The first two define the limits for the fields value. and ``decimal_places``. The first two define the limits for the fields value.
Expand All @@ -1251,6 +1283,7 @@ decimal places permitted.
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates that the given value is a valid e-mail address, using a * Validates that the given value is a valid e-mail address, using a
moderately complex regular expression. moderately complex regular expression.
* Error message keys: ``required``, ``invalid``


Has two optional arguments for validation, ``max_length`` and ``min_length``. Has two optional arguments for validation, ``max_length`` and ``min_length``.
If provided, these arguments ensure that the string is at most or at least the If provided, these arguments ensure that the string is at most or at least the
Expand All @@ -1266,6 +1299,7 @@ given length.
* Normalizes to: An ``UploadedFile`` object that wraps the file content * Normalizes to: An ``UploadedFile`` object that wraps the file content
and file name into a single object. and file name into a single object.
* Validates that non-empty file data has been bound to the form. * Validates that non-empty file data has been bound to the form.
* Error message keys: ``required``, ``invalid``, ``missing``, ``empty``


An ``UploadedFile`` object has two attributes: An ``UploadedFile`` object has two attributes:


Expand Down Expand Up @@ -1296,6 +1330,8 @@ When you use a ``FileField`` on a form, you must also remember to
and file name into a single object. and file name into a single object.
* Validates that file data has been bound to the form, and that the * Validates that file data has been bound to the form, and that the
file is of an image format understood by PIL. file is of an image format understood by PIL.
* Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
``invalid_image``


Using an ImageField requires that the `Python Imaging Library`_ is installed. Using an ImageField requires that the `Python Imaging Library`_ is installed.


Expand All @@ -1312,6 +1348,8 @@ When you use a ``FileField`` on a form, you must also remember to
* Normalizes to: A Python integer or long integer. * Normalizes to: A Python integer or long integer.
* Validates that the given value is an integer. Leading and trailing * Validates that the given value is an integer. Leading and trailing
whitespace is allowed, as in Python's ``int()`` function. whitespace is allowed, as in Python's ``int()`` function.
* Error message keys: ``required``, ``invalid``, ``max_value``,
``min_value``


Takes two optional arguments for validation, ``max_value`` and ``min_value``. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
These control the range of values permitted in the field. These control the range of values permitted in the field.
Expand All @@ -1324,6 +1362,7 @@ These control the range of values permitted in the field.
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates that the given value is a valid IPv4 address, using a regular * Validates that the given value is a valid IPv4 address, using a regular
expression. expression.
* Error message keys: ``required``, ``invalid``


``MultipleChoiceField`` ``MultipleChoiceField``
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -1333,6 +1372,7 @@ These control the range of values permitted in the field.
* Normalizes to: A list of Unicode objects. * Normalizes to: A list of Unicode objects.
* Validates that every value in the given list of values exists in the list * Validates that every value in the given list of values exists in the list
of choices. of choices.
* Error message keys: ``required``, ``invalid_choice``, ``invalid_list``


Takes one extra argument, ``choices``, which is an iterable (e.g., a list or Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
tuple) of 2-tuples to use as choices for this field. tuple) of 2-tuples to use as choices for this field.
Expand All @@ -1353,6 +1393,7 @@ tuple) of 2-tuples to use as choices for this field.
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates that the given value matches against a certain regular * Validates that the given value matches against a certain regular
expression. expression.
* Error message keys: ``required``, ``invalid``


Takes one required argument, ``regex``, which is a regular expression specified Takes one required argument, ``regex``, which is a regular expression specified
either as a string or a compiled regular expression object. either as a string or a compiled regular expression object.
Expand All @@ -1364,11 +1405,13 @@ Also takes the following optional arguments:
====================== ===================================================== ====================== =====================================================
``max_length`` Ensures the string has at most this many characters. ``max_length`` Ensures the string has at most this many characters.
``min_length`` Ensures the string has at least this many characters. ``min_length`` Ensures the string has at least this many characters.
``error_message`` Error message to return for failed validation. If no
message is provided, a generic error message will be
used.
====================== ===================================================== ====================== =====================================================


The optional argument ``error_message`` is also accepted for backwards
compatibility. The preferred way to provide an error message is to use the
``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
and the error message as the value.

``TimeField`` ``TimeField``
~~~~~~~~~~~~~ ~~~~~~~~~~~~~


Expand All @@ -1377,6 +1420,7 @@ Also takes the following optional arguments:
* Normalizes to: A Python ``datetime.time`` object. * Normalizes to: A Python ``datetime.time`` object.
* Validates that the given value is either a ``datetime.time`` or string * Validates that the given value is either a ``datetime.time`` or string
formatted in a particular time format. formatted in a particular time format.
* Error message keys: ``required``, ``invalid``


Takes one optional argument, ``input_formats``, which is a list of formats used Takes one optional argument, ``input_formats``, which is a list of formats used
to attempt to convert a string to a valid ``datetime.time`` object. to attempt to convert a string to a valid ``datetime.time`` object.
Expand All @@ -1393,6 +1437,7 @@ If no ``input_formats`` argument is provided, the default input formats are::
* Empty value: ``''`` (an empty string) * Empty value: ``''`` (an empty string)
* Normalizes to: A Unicode object. * Normalizes to: A Unicode object.
* Validates that the given value is a valid URL. * Validates that the given value is a valid URL.
* Error message keys: ``required``, ``invalid``, ``invalid_link``


Takes the following optional arguments: Takes the following optional arguments:


Expand Down

0 comments on commit 26ea06b

Please sign in to comment.