12
12
directly), but normally they won't be needed.
14
14
In general, any cleaning method can raise ``ValidationError`` if there is a
15
problem with the data it is processing, passing the relevant error message to
16
the ``ValidationError`` constructor. If no ``ValidationError`` is raised, the
17
method should return the cleaned (normalized) data as a Python object.
19
If you detect multiple errors during a cleaning method and wish to signal all
20
of them to the form submitter, it is possible to pass a list of errors to the
21
``ValidationError`` constructor.
15
problem with the data it is processing, passing the relevant information to
16
the ``ValidationError`` constructor. :ref:`See below <raising-validation-error>`
17
for the best practice in raising ``ValidationError``. If no ``ValidationError``
18
is raised, the method should return the cleaned (normalized) data as a Python
23
21
Most validation can be done using `validators`_ - simple helpers that can be
24
22
reused easily. Validators are simple functions (or callables) that take a single
87
85
"field" (called ``__all__``), which you can access via the
88
86
``non_field_errors()`` method if you need to. If you want to attach
89
87
errors to a specific field in the form, you will need to access the
90
``_errors`` attribute on the form, which is `described later`_.
88
``_errors`` attribute on the form, which is
89
:ref:`described later <modifying-field-errors>`.
92
91
Also note that there are special considerations when overriding
93
92
the ``clean()`` method of a ``ModelForm`` subclass. (see the
116
115
``_errors`` dictionary attribute on the form as well. In this way, you will
117
116
already know which fields have passed their individual validation requirements.
118
.. _raising-validation-error:
120
Raising ``ValidationError``
121
---------------------------
123
.. versionchanged:: 1.6
125
In order to make error messages flexible and easy to override, consider the
126
following guidelines:
128
* Provide a descriptive error ``code`` to the constructor::
131
ValidationError(_('Invalid value'), code='invalid')
134
ValidationError(_('Invalid value'))
136
* Don't coerce variables into the message; use placeholders and the ``params``
137
argument of the constructor::
141
_('Invalid value: %(value)s'),
142
params={'value': '42'},
146
ValidationError(_('Invalid value: %s') % value)
148
* Use mapping keys instead of positional formatting. This enables putting
149
the variables in any order or omitting them altogether when rewriting the
154
_('Invalid value: %(value)s'),
155
params={'value': '42'},
160
_('Invalid value: %s'),
164
* Wrap the message with ``gettext`` to enable translation::
167
ValidationError(_('Invalid value'))
170
ValidationError('Invalid value')
172
Putting it all together::
174
raise ValidationError(
175
_('Invalid value: %(value)s'),
177
params={'value': '42'},
180
Following these guidelines is particularly necessary if you write reusable
181
forms, form fields, and model fields.
183
While not recommended, if you are at the end of the validation chain
184
(i.e. your form ``clean()`` method) and you know you will *never* need
185
to override your error message you can still opt for the less verbose::
187
ValidationError(_('Invalid value: %s') % value)
189
Raising multiple errors
190
~~~~~~~~~~~~~~~~~~~~~~~
192
If you detect multiple errors during a cleaning method and wish to signal all
193
of them to the form submitter, it is possible to pass a list of errors to the
194
``ValidationError`` constructor.
196
As above, it is recommended to pass a list of ``ValidationError`` instances
197
with ``code``\s and ``params`` but a list of strings will also work::
200
raise ValidationError([
201
ValidationError(_('Error 1'), code='error1'),
202
ValidationError(_('Error 2'), code='error2'),
206
raise ValidationError([
211
.. _modifying-field-errors:
121
213
Form subclasses and modifying field errors
122
214
------------------------------------------
178
270
Django's form (and model) fields support use of simple utility functions and
179
classes known as validators. These can be passed to a field's constructor, via
180
the field's ``validators`` argument, or defined on the Field class itself with
181
the ``default_validators`` attribute.
271
classes known as validators. A validator is merely a callable object or
272
function that takes a value and simply returns nothing if the value is valid or
273
raises a :exc:`~django.core.exceptions.ValidationError` if not. These can be
274
passed to a field's constructor, via the field's ``validators`` argument, or
275
defined on the :class:`~django.forms.Field` class itself with the
276
``default_validators`` attribute.
183
278
Simple validators can be used to validate values inside the field, let's have
184
a look at Django's ``EmailField``::
186
class EmailField(CharField):
187
default_error_messages = {
188
'invalid': _('Enter a valid email address.'),
190
default_validators = [validators.validate_email]
192
As you can see, ``EmailField`` is just a ``CharField`` with customized error
193
message and a validator that validates email addresses. This can also be done
194
on field definition so::
196
email = forms.EmailField()
279
a look at Django's ``SlugField``::
281
from django.forms import CharField
282
from django.core import validators
284
class SlugField(CharField):
285
default_validators = [validators.validate_slug]
287
As you can see, ``SlugField`` is just a ``CharField`` with a customized
288
validator that validates that submitted text obeys to some character rules.
289
This can also be done on field definition so::
291
slug = forms.SlugField()
198
293
is equivalent to::
200
email = forms.CharField(validators=[validators.validate_email],
201
error_messages={'invalid': _('Enter a valid email address.')})
295
slug = forms.CharField(validators=[validators.validate_slug])
297
Common cases such as validating against an email or a regular expression can be
298
handled using existing validator classes available in Django. For example,
299
``validators.validate_slug`` is an instance of
300
a :class:`~django.core.validators.RegexValidator` constructed with the first
301
argument being the pattern: ``^[-a-zA-Z0-9_]+$``. See the section on
302
:doc:`writing validators </ref/validators>` to see a list of what is already
303
available and for an example of how to write a validator.
204
305
Form field default cleaning
205
306
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
366
473
.. versionchanged:: 1.5
368
Django used to remove the ``cleaned_data`` attribute entirely if there were
369
any errors in the form. Since version 1.5, ``cleaned_data`` is present even if
370
the form doesn't validate, but it contains only field values that did
475
Django used to remove the ``cleaned_data`` attribute entirely if there were
476
any errors in the form. Since version 1.5, ``cleaned_data`` is present even if
477
the form doesn't validate, but it contains only field values that did