~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to docs/ref/forms/validation.txt

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
directly), but normally they won't be needed.
13
13
 
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.
18
 
 
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
 
19
object.
22
20
 
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>`.
91
90
 
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
117
 
119
 
.. _described later:
 
118
.. _raising-validation-error:
 
119
 
 
120
Raising ``ValidationError``
 
121
---------------------------
 
122
 
 
123
.. versionchanged:: 1.6
 
124
 
 
125
In order to make error messages flexible and easy to override, consider the
 
126
following guidelines:
 
127
 
 
128
* Provide a descriptive error ``code`` to the constructor::
 
129
 
 
130
      # Good
 
131
      ValidationError(_('Invalid value'), code='invalid')
 
132
 
 
133
      # Bad
 
134
      ValidationError(_('Invalid value'))
 
135
 
 
136
* Don't coerce variables into the message; use placeholders and the ``params``
 
137
  argument of the constructor::
 
138
 
 
139
      # Good
 
140
      ValidationError(
 
141
          _('Invalid value: %(value)s'),
 
142
          params={'value': '42'},
 
143
      )
 
144
 
 
145
      # Bad
 
146
      ValidationError(_('Invalid value: %s') % value)
 
147
 
 
148
* Use mapping keys instead of positional formatting. This enables putting
 
149
  the variables in any order or omitting them altogether when rewriting the
 
150
  message::
 
151
 
 
152
      # Good
 
153
      ValidationError(
 
154
          _('Invalid value: %(value)s'),
 
155
          params={'value': '42'},
 
156
      )
 
157
 
 
158
      # Bad
 
159
      ValidationError(
 
160
          _('Invalid value: %s'),
 
161
          params=('42',),
 
162
      )
 
163
 
 
164
* Wrap the message with ``gettext`` to enable translation::
 
165
 
 
166
      # Good
 
167
      ValidationError(_('Invalid value'))
 
168
 
 
169
      # Bad
 
170
      ValidationError('Invalid value')
 
171
 
 
172
Putting it all together::
 
173
 
 
174
    raise ValidationError(
 
175
        _('Invalid value: %(value)s'),
 
176
        code='invalid',
 
177
        params={'value': '42'},
 
178
    )
 
179
 
 
180
Following these guidelines is particularly necessary if you write reusable
 
181
forms, form fields, and model fields.
 
182
 
 
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::
 
186
 
 
187
    ValidationError(_('Invalid value: %s') % value)
 
188
 
 
189
Raising multiple errors
 
190
~~~~~~~~~~~~~~~~~~~~~~~
 
191
 
 
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.
 
195
 
 
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::
 
198
 
 
199
    # Good
 
200
    raise ValidationError([
 
201
        ValidationError(_('Error 1'), code='error1'),
 
202
        ValidationError(_('Error 2'), code='error2'),
 
203
    ])
 
204
 
 
205
    # Bad
 
206
    raise ValidationError([
 
207
        _('Error 1'),
 
208
        _('Error 2'),
 
209
    ])
 
210
 
 
211
.. _modifying-field-errors:
120
212
 
121
213
Form subclasses and modifying field errors
122
214
------------------------------------------
176
268
~~~~~~~~~~~~~~~~
177
269
 
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.
182
277
 
183
278
Simple validators can be used to validate values inside the field, let's have
184
 
a look at Django's ``EmailField``::
185
 
 
186
 
    class EmailField(CharField):
187
 
        default_error_messages = {
188
 
            'invalid': _('Enter a valid email address.'),
189
 
        }
190
 
        default_validators = [validators.validate_email]
191
 
 
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::
195
 
 
196
 
    email = forms.EmailField()
 
279
a look at Django's ``SlugField``::
 
280
 
 
281
    from django.forms import CharField
 
282
    from django.core import validators
 
283
 
 
284
    class SlugField(CharField):
 
285
        default_validators = [validators.validate_slug]
 
286
 
 
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::
 
290
 
 
291
    slug = forms.SlugField()
197
292
 
198
293
is equivalent to::
199
294
 
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])
202
296
 
 
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.
203
304
 
204
305
Form field default cleaning
205
306
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256
357
don't want to put it into the general ``MultiEmailField`` class. Instead, we
257
358
write a cleaning method that operates on the ``recipients`` field, like so::
258
359
 
 
360
    from django import forms
 
361
 
259
362
    class ContactForm(forms.Form):
260
363
        # Everything as before.
261
364
        ...
295
398
an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
296
399
example::
297
400
 
 
401
    from django import forms
 
402
 
298
403
    class ContactForm(forms.Form):
299
404
        # Everything as before.
300
405
        ...
327
432
effectively in your particular situation. Our new code (replacing the previous
328
433
sample) looks like this::
329
434
 
 
435
    from django import forms
 
436
 
330
437
    class ContactForm(forms.Form):
331
438
        # Everything as before.
332
439
        ...
365
472
 
366
473
.. versionchanged:: 1.5
367
474
 
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
371
 
validate.
 
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
 
478
    validate.