validation.txt 19 KB

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