| 1 |
========================= |
| 2 |
Form and field validation |
| 3 |
========================= |
| 4 |
|
| 5 |
.. currentmodule:: django.forms |
| 6 |
|
| 7 |
Form validation happens when the data is cleaned. If you want to customize |
| 8 |
this process, there are various places to make changes, each one serving a |
| 9 |
different purpose. Three types of cleaning methods are run during form |
| 10 |
processing. These are normally executed when you call the ``is_valid()`` |
| 11 |
method on a form. There are other things that can also trigger cleaning and |
| 12 |
validation (accessing the ``errors`` attribute or calling ``full_clean()`` |
| 13 |
directly), but normally they won't be needed. |
| 14 |
|
| 15 |
In general, any cleaning method can raise ``ValidationError`` if there is a |
| 16 |
problem with the data it is processing, passing the relevant information to |
| 17 |
the ``ValidationError`` constructor. :ref:`See below <raising-validation-error>` |
| 18 |
for the best practice in raising ``ValidationError``. If no ``ValidationError`` |
| 19 |
is raised, the method should return the cleaned (normalized) data as a Python |
| 20 |
object. |
| 21 |
|
| 22 |
Most validation can be done using `validators`_ - helpers that can be reused. |
| 23 |
Validators are functions (or callables) that take a single argument and raise |
| 24 |
``ValidationError`` on invalid input. Validators are run after the field's |
| 25 |
``to_python`` and ``validate`` methods have been called. |
| 26 |
|
| 27 |
Validation of a form is split into several steps, which can be customized or |
| 28 |
overridden: |
| 29 |
|
| 30 |
* The ``to_python()`` method on a ``Field`` is the first step in every |
| 31 |
validation. It coerces the value to a correct datatype and raises |
| 32 |
``ValidationError`` if that is not possible. This method accepts the raw |
| 33 |
value from the widget and returns the converted value. For example, a |
| 34 |
``FloatField`` will turn the data into a Python ``float`` or raise a |
| 35 |
``ValidationError``. |
| 36 |
|
| 37 |
* The ``validate()`` method on a ``Field`` handles field-specific validation |
| 38 |
that is not suitable for a validator. It takes a value that has been |
| 39 |
coerced to a correct datatype and raises ``ValidationError`` on any error. |
| 40 |
This method does not return anything and shouldn't alter the value. You |
| 41 |
should override it to handle validation logic that you can't or don't |
| 42 |
want to put in a validator. |
| 43 |
|
| 44 |
* The ``run_validators()`` method on a ``Field`` runs all of the field's |
| 45 |
validators and aggregates all the errors into a single |
| 46 |
``ValidationError``. You shouldn't need to override this method. |
| 47 |
|
| 48 |
* The ``clean()`` method on a ``Field`` subclass is responsible for running |
| 49 |
``to_python()``, ``validate()``, and ``run_validators()`` in the correct |
| 50 |
order and propagating their errors. If, at any time, any of the methods |
| 51 |
raise ``ValidationError``, the validation stops and that error is raised. |
| 52 |
This method returns the clean data, which is then inserted into the |
| 53 |
``cleaned_data`` dictionary of the form. |
| 54 |
|
| 55 |
* The ``clean_<fieldname>()`` method is called on a form subclass -- where |
| 56 |
``<fieldname>`` is replaced with the name of the form field attribute. |
| 57 |
This method does any cleaning that is specific to that particular |
| 58 |
attribute, unrelated to the type of field that it is. This method is not |
| 59 |
passed any parameters. You will need to look up the value of the field |
| 60 |
in ``self.cleaned_data`` and remember that it will be a Python object |
| 61 |
at this point, not the original string submitted in the form (it will be |
| 62 |
in ``cleaned_data`` because the general field ``clean()`` method, above, |
| 63 |
has already cleaned the data once). |
| 64 |
|
| 65 |
For example, if you wanted to validate that the contents of a |
| 66 |
``CharField`` called ``serialnumber`` was unique, |
| 67 |
``clean_serialnumber()`` would be the right place to do this. You don't |
| 68 |
need a specific field (it's a ``CharField``), but you want a |
| 69 |
formfield-specific piece of validation and, possibly, cleaning/normalizing |
| 70 |
the data. |
| 71 |
|
| 72 |
The return value of this method replaces the existing value in |
| 73 |
``cleaned_data``, so it must be the field's value from ``cleaned_data`` (even |
| 74 |
if this method didn't change it) or a new cleaned value. |
| 75 |
|
| 76 |
* The form subclass's ``clean()`` method can perform validation that requires |
| 77 |
access to multiple form fields. This is where you might put in checks such as |
| 78 |
"if field ``A`` is supplied, field ``B`` must contain a valid email address". |
| 79 |
This method can return a completely different dictionary if it wishes, which |
| 80 |
will be used as the ``cleaned_data``. |
| 81 |
|
| 82 |
Since the field validation methods have been run by the time ``clean()`` is |
| 83 |
called, you also have access to the form's ``errors`` attribute which |
| 84 |
contains all the errors raised by cleaning of individual fields. |
| 85 |
|
| 86 |
Note that any errors raised by your :meth:`Form.clean()` override will not |
| 87 |
be associated with any field in particular. They go into a special |
| 88 |
"field" (called ``__all__``), which you can access via the |
| 89 |
:meth:`~django.forms.Form.non_field_errors` method if you need to. If you |
| 90 |
want to attach errors to a specific field in the form, you need to call |
| 91 |
:meth:`~django.forms.Form.add_error()`. |
| 92 |
|
| 93 |
Also note that there are special considerations when overriding |
| 94 |
the ``clean()`` method of a ``ModelForm`` subclass. (see the |
| 95 |
:ref:`ModelForm documentation |
| 96 |
<overriding-modelform-clean-method>` for more information) |
| 97 |
|
| 98 |
These methods are run in the order given above, one field at a time. That is, |
| 99 |
for each field in the form (in the order they are declared in the form |
| 100 |
definition), the ``Field.clean()`` method (or its override) is run, then |
| 101 |
``clean_<fieldname>()``. Finally, once those two methods are run for every |
| 102 |
field, the :meth:`Form.clean()` method, or its override, is executed whether |
| 103 |
or not the previous methods have raised errors. |
| 104 |
|
| 105 |
Examples of each of these methods are provided below. |
| 106 |
|
| 107 |
As mentioned, any of these methods can raise a ``ValidationError``. For any |
| 108 |
field, if the ``Field.clean()`` method raises a ``ValidationError``, any |
| 109 |
field-specific cleaning method is not called. However, the cleaning methods |
| 110 |
for all remaining fields are still executed. |
| 111 |
|
| 112 |
.. _raising-validation-error: |
| 113 |
|
| 114 |
Raising ``ValidationError`` |
| 115 |
=========================== |
| 116 |
|
| 117 |
In order to make error messages flexible and easy to override, consider the |
| 118 |
following guidelines: |
| 119 |
|
| 120 |
* Provide a descriptive error ``code`` to the constructor:: |
| 121 |
|
| 122 |
# Good |
| 123 |
ValidationError(_("Invalid value"), code="invalid") |
| 124 |
|
| 125 |
# Bad |
| 126 |
ValidationError(_("Invalid value")) |
| 127 |
|
| 128 |
* Don't coerce variables into the message; use placeholders and the ``params`` |
| 129 |
argument of the constructor:: |
| 130 |
|
| 131 |
# Good |
| 132 |
ValidationError( |
| 133 |
_("Invalid value: %(value)s"), |
| 134 |
params={"value": "42"}, |
| 135 |
) |
| 136 |
|
| 137 |
# Bad |
| 138 |
ValidationError(_("Invalid value: %s") % value) |
| 139 |
|
| 140 |
* Use mapping keys instead of positional formatting. This enables putting |
| 141 |
the variables in any order or omitting them altogether when rewriting the |
| 142 |
message:: |
| 143 |
|
| 144 |
# Good |
| 145 |
ValidationError( |
| 146 |
_("Invalid value: %(value)s"), |
| 147 |
params={"value": "42"}, |
| 148 |
) |
| 149 |
|
| 150 |
# Bad |
| 151 |
ValidationError( |
| 152 |
_("Invalid value: %s"), |
| 153 |
params=("42",), |
| 154 |
) |
| 155 |
|
| 156 |
* Wrap the message with ``gettext`` to enable translation:: |
| 157 |
|
| 158 |
# Good |
| 159 |
ValidationError(_("Invalid value")) |
| 160 |
|
| 161 |
# Bad |
| 162 |
ValidationError("Invalid value") |
| 163 |
|
| 164 |
Putting it all together:: |
| 165 |
|
| 166 |
raise ValidationError( |
| 167 |
_("Invalid value: %(value)s"), |
| 168 |
code="invalid", |
| 169 |
params={"value": "42"}, |
| 170 |
) |
| 171 |
|
| 172 |
Following these guidelines is particularly necessary if you write reusable |
| 173 |
forms, form fields, and model fields. |
| 174 |
|
| 175 |
While not recommended, if you are at the end of the validation chain |
| 176 |
(i.e. your form ``clean()`` method) and you know you will *never* need |
| 177 |
to override your error message you can still opt for the less verbose:: |
| 178 |
|
| 179 |
ValidationError(_("Invalid value: %s") % value) |
| 180 |
|
| 181 |
The :meth:`Form.errors.as_data() <django.forms.Form.errors.as_data()>` and |
| 182 |
:meth:`Form.errors.as_json() <django.forms.Form.errors.as_json()>` methods |
| 183 |
greatly benefit from fully featured ``ValidationError``\s (with a ``code`` name |
| 184 |
and a ``params`` dictionary). |
| 185 |
|
| 186 |
Raising multiple errors |
| 187 |
----------------------- |
| 188 |
|
| 189 |
If you detect multiple errors during a cleaning method and wish to signal all |
| 190 |
of them to the form submitter, it is possible to pass a list of errors to the |
| 191 |
``ValidationError`` constructor. |
| 192 |
|
| 193 |
As above, it is recommended to pass a list of ``ValidationError`` instances |
| 194 |
with ``code``\s and ``params`` but a list of strings will also work:: |
| 195 |
|
| 196 |
# Good |
| 197 |
raise ValidationError( |
| 198 |
[ |
| 199 |
ValidationError(_("Error 1"), code="error1"), |
| 200 |
ValidationError(_("Error 2"), code="error2"), |
| 201 |
] |
| 202 |
) |
| 203 |
|
| 204 |
# Bad |
| 205 |
raise ValidationError( |
| 206 |
[ |
| 207 |
_("Error 1"), |
| 208 |
_("Error 2"), |
| 209 |
] |
| 210 |
) |
| 211 |
|
| 212 |
Using validation in practice |
| 213 |
============================ |
| 214 |
|
| 215 |
The previous sections explained how validation works in general for forms. |
| 216 |
Since it can sometimes be easier to put things into place by seeing each |
| 217 |
feature in use, here are a series of small examples that use each of the |
| 218 |
previous features. |
| 219 |
|
| 220 |
.. _validators: |
| 221 |
|
| 222 |
Using validators |
| 223 |
---------------- |
| 224 |
|
| 225 |
Django's form (and model) fields support use of utility functions and classes |
| 226 |
known as validators. A validator is a callable object or function that takes a |
| 227 |
value and returns nothing if the value is valid or raises a |
| 228 |
:exc:`~django.core.exceptions.ValidationError` if not. These can be passed to a |
| 229 |
field's constructor, via the field's ``validators`` argument, or defined on the |
| 230 |
:class:`~django.forms.Field` class itself with the ``default_validators`` |
| 231 |
attribute. |
| 232 |
|
| 233 |
Validators can be used to validate values inside the field, let's have a look |
| 234 |
at Django's ``SlugField``:: |
| 235 |
|
| 236 |
from django.core import validators |
| 237 |
from django.forms import CharField |
| 238 |
|
| 239 |
|
| 240 |
class SlugField(CharField): |
| 241 |
default_validators = [validators.validate_slug] |
| 242 |
|
| 243 |
As you can see, ``SlugField`` is a ``CharField`` with a customized validator |
| 244 |
that validates that submitted text obeys to some character rules. This can also |
| 245 |
be done on field definition so:: |
| 246 |
|
| 247 |
slug = forms.SlugField() |
| 248 |
|
| 249 |
is equivalent to:: |
| 250 |
|
| 251 |
slug = forms.CharField(validators=[validators.validate_slug]) |
| 252 |
|
| 253 |
Common cases such as validating against an email or a regular expression can be |
| 254 |
handled using existing validator classes available in Django. For example, |
| 255 |
``validators.validate_slug`` is an instance of |
| 256 |
a :class:`~django.core.validators.RegexValidator` constructed with the first |
| 257 |
argument being the pattern: ``^[-a-zA-Z0-9_]+\Z``. See the section on |
| 258 |
:doc:`writing validators </ref/validators>` to see a list of what is already |
| 259 |
available and for an example of how to write a validator. |
| 260 |
|
| 261 |
Form field default cleaning |
| 262 |
--------------------------- |
| 263 |
|
| 264 |
Let's first create a custom form field that validates its input is a string |
| 265 |
containing comma-separated email addresses. The full class looks like this:: |
| 266 |
|
| 267 |
from django import forms |
| 268 |
from django.core.validators import validate_email |
| 269 |
|
| 270 |
|
| 271 |
class MultiEmailField(forms.Field): |
| 272 |
def to_python(self, value): |
| 273 |
"""Normalize data to a list of strings.""" |
| 274 |
# Return an empty list if no input was given. |
| 275 |
if not value: |
| 276 |
return [] |
| 277 |
return value.split(",") |
| 278 |
|
| 279 |
def validate(self, value): |
| 280 |
"""Check if value consists only of valid emails.""" |
| 281 |
# Use the parent's handling of required fields, etc. |
| 282 |
super().validate(value) |
| 283 |
for email in value: |
| 284 |
validate_email(email) |
| 285 |
|
| 286 |
Every form that uses this field will have these methods run before anything |
| 287 |
else can be done with the field's data. This is cleaning that is specific to |
| 288 |
this type of field, regardless of how it is subsequently used. |
| 289 |
|
| 290 |
Let's create a ``ContactForm`` to demonstrate how you'd use this field:: |
| 291 |
|
| 292 |
class ContactForm(forms.Form): |
| 293 |
subject = forms.CharField(max_length=100) |
| 294 |
message = forms.CharField() |
| 295 |
sender = forms.EmailField() |
| 296 |
recipients = MultiEmailField() |
| 297 |
cc_myself = forms.BooleanField(required=False) |
| 298 |
|
| 299 |
Use ``MultiEmailField`` like any other form field. When the ``is_valid()`` |
| 300 |
method is called on the form, the ``MultiEmailField.clean()`` method will be |
| 301 |
run as part of the cleaning process and it will, in turn, call the custom |
| 302 |
``to_python()`` and ``validate()`` methods. |
| 303 |
|
| 304 |
Cleaning a specific field attribute |
| 305 |
----------------------------------- |
| 306 |
|
| 307 |
Continuing on from the previous example, suppose that in our ``ContactForm``, |
| 308 |
we want to make sure that the ``recipients`` field always contains the address |
| 309 |
``"[email protected]"``. This is validation that is specific to our form, so we |
| 310 |
don't want to put it into the general ``MultiEmailField`` class. Instead, we |
| 311 |
write a cleaning method that operates on the ``recipients`` field, like so:: |
| 312 |
|
| 313 |
from django import forms |
| 314 |
from django.core.exceptions import ValidationError |
| 315 |
|
| 316 |
|
| 317 |
class ContactForm(forms.Form): |
| 318 |
# Everything as before. |
| 319 |
... |
| 320 |
|
| 321 |
def clean_recipients(self): |
| 322 |
data = self.cleaned_data["recipients"] |
| 323 |
if "[email protected]" not in data: |
| 324 |
raise ValidationError("You have forgotten about Fred!") |
| 325 |
|
| 326 |
# Always return a value to use as the new cleaned data, even if |
| 327 |
# this method didn't change it. |
| 328 |
return data |
| 329 |
|
| 330 |
.. _validating-fields-with-clean: |
| 331 |
|
| 332 |
Cleaning and validating fields that depend on each other |
| 333 |
-------------------------------------------------------- |
| 334 |
|
| 335 |
Suppose we add another requirement to our contact form: if the ``cc_myself`` |
| 336 |
field is ``True``, the ``subject`` must contain the word ``"help"``. We are |
| 337 |
performing validation on more than one field at a time, so the form's |
| 338 |
:meth:`~Form.clean()` method is a good spot to do this. Notice that we are |
| 339 |
talking about the ``clean()`` method on the form here, whereas earlier we were |
| 340 |
writing a ``clean()`` method on a field. It's important to keep the field and |
| 341 |
form difference clear when working out where to validate things. Fields are |
| 342 |
single data points, forms are a collection of fields. |
| 343 |
|
| 344 |
By the time the form's ``clean()`` method is called, all the individual field |
| 345 |
clean methods will have been run (the previous two sections), so |
| 346 |
``self.cleaned_data`` will be populated with any data that has survived so |
| 347 |
far. So you also need to remember to allow for the fact that the fields you |
| 348 |
are wanting to validate might not have survived the initial individual field |
| 349 |
checks. |
| 350 |
|
| 351 |
There are two ways to report any errors from this step. Probably the most |
| 352 |
common method is to display the error at the top of the form. To create such |
| 353 |
an error, you can raise a ``ValidationError`` from the ``clean()`` method. For |
| 354 |
example:: |
| 355 |
|
| 356 |
from django import forms |
| 357 |
from django.core.exceptions import ValidationError |
| 358 |
|
| 359 |
|
| 360 |
class ContactForm(forms.Form): |
| 361 |
# Everything as before. |
| 362 |
... |
| 363 |
|
| 364 |
def clean(self): |
| 365 |
cleaned_data = super().clean() |
| 366 |
cc_myself = cleaned_data.get("cc_myself") |
| 367 |
subject = cleaned_data.get("subject") |
| 368 |
|
| 369 |
if cc_myself and subject: |
| 370 |
# Only do something if both fields are valid so far. |
| 371 |
if "help" not in subject: |
| 372 |
raise ValidationError( |
| 373 |
"Did not send for 'help' in the subject despite CC'ing yourself." |
| 374 |
) |
| 375 |
|
| 376 |
In this code, if the validation error is raised, the form will display an |
| 377 |
error message at the top of the form (normally) describing the problem. Such |
| 378 |
errors are non-field errors, which are displayed in the template with |
| 379 |
``{{ form.non_field_errors }}``. |
| 380 |
|
| 381 |
The call to ``super().clean()`` in the example code ensures that any validation |
| 382 |
logic in parent classes is maintained. If your form inherits another that |
| 383 |
doesn't return a ``cleaned_data`` dictionary in its ``clean()`` method (doing |
| 384 |
so is optional), then don't assign ``cleaned_data`` to the result of the |
| 385 |
``super()`` call and use ``self.cleaned_data`` instead:: |
| 386 |
|
| 387 |
def clean(self): |
| 388 |
super().clean() |
| 389 |
cc_myself = self.cleaned_data.get("cc_myself") |
| 390 |
... |
| 391 |
|
| 392 |
The second approach for reporting validation errors might involve assigning the |
| 393 |
error message to one of the fields. In this case, let's assign an error message |
| 394 |
to both the "subject" and "cc_myself" rows in the form display. Be careful when |
| 395 |
doing this in practice, since it can lead to confusing form output. We're |
| 396 |
showing what is possible here and leaving it up to you and your designers to |
| 397 |
work out what works effectively in your particular situation. Our new code |
| 398 |
(replacing the previous sample) looks like this:: |
| 399 |
|
| 400 |
from django import forms |
| 401 |
|
| 402 |
|
| 403 |
class ContactForm(forms.Form): |
| 404 |
# Everything as before. |
| 405 |
... |
| 406 |
|
| 407 |
def clean(self): |
| 408 |
cleaned_data = super().clean() |
| 409 |
cc_myself = cleaned_data.get("cc_myself") |
| 410 |
subject = cleaned_data.get("subject") |
| 411 |
|
| 412 |
if cc_myself and subject and "help" not in subject: |
| 413 |
msg = "Must put 'help' in subject when cc'ing yourself." |
| 414 |
self.add_error("cc_myself", msg) |
| 415 |
self.add_error("subject", msg) |
| 416 |
|
| 417 |
The second argument of ``add_error()`` can be a string, or preferably an |
| 418 |
instance of ``ValidationError``. See :ref:`raising-validation-error` for more |
| 419 |
details. Note that ``add_error()`` automatically removes the field from |
| 420 |
``cleaned_data``. |