validation.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 methods 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 cleaning of individual fields.
  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. :meth:`~django.forms.Form.non_field_errors` method if you need to. If you
  74. want to attach errors to a specific field in the form, you need to call
  75. :meth:`~django.forms.Form.add_error()`.
  76. Also note that there are special considerations when overriding
  77. the ``clean()`` method of a ``ModelForm`` subclass. (see the
  78. :ref:`ModelForm documentation
  79. <overriding-modelform-clean-method>` for more information)
  80. These methods are run in the order given above, one field at a time. That is,
  81. for each field in the form (in the order they are declared in the form
  82. definition), the ``Field.clean()`` method (or its override) is run, then
  83. ``clean_<fieldname>()``. Finally, once those two methods are run for every
  84. field, the ``Form.clean()`` method, or its override, is executed whether or not
  85. the previous methods have raised errors.
  86. Examples of each of these methods are provided below.
  87. As mentioned, any of these methods can raise a ``ValidationError``. For any
  88. field, if the ``Field.clean()`` method raises a ``ValidationError``, any
  89. field-specific cleaning method is not called. However, the cleaning methods
  90. for all remaining fields are still executed.
  91. .. _raising-validation-error:
  92. Raising ``ValidationError``
  93. ---------------------------
  94. In order to make error messages flexible and easy to override, consider the
  95. following guidelines:
  96. * Provide a descriptive error ``code`` to the constructor::
  97. # Good
  98. ValidationError(_('Invalid value'), code='invalid')
  99. # Bad
  100. ValidationError(_('Invalid value'))
  101. * Don't coerce variables into the message; use placeholders and the ``params``
  102. argument of the constructor::
  103. # Good
  104. ValidationError(
  105. _('Invalid value: %(value)s'),
  106. params={'value': '42'},
  107. )
  108. # Bad
  109. ValidationError(_('Invalid value: %s') % value)
  110. * Use mapping keys instead of positional formatting. This enables putting
  111. the variables in any order or omitting them altogether when rewriting the
  112. message::
  113. # Good
  114. ValidationError(
  115. _('Invalid value: %(value)s'),
  116. params={'value': '42'},
  117. )
  118. # Bad
  119. ValidationError(
  120. _('Invalid value: %s'),
  121. params=('42',),
  122. )
  123. * Wrap the message with ``gettext`` to enable translation::
  124. # Good
  125. ValidationError(_('Invalid value'))
  126. # Bad
  127. ValidationError('Invalid value')
  128. Putting it all together::
  129. raise ValidationError(
  130. _('Invalid value: %(value)s'),
  131. code='invalid',
  132. params={'value': '42'},
  133. )
  134. Following these guidelines is particularly necessary if you write reusable
  135. forms, form fields, and model fields.
  136. While not recommended, if you are at the end of the validation chain
  137. (i.e. your form ``clean()`` method) and you know you will *never* need
  138. to override your error message you can still opt for the less verbose::
  139. ValidationError(_('Invalid value: %s') % value)
  140. .. versionadded:: 1.7
  141. The :meth:`Form.errors.as_data() <django.forms.Form.errors.as_data()>` and
  142. :meth:`Form.errors.as_json() <django.forms.Form.errors.as_json()>` methods
  143. greatly benefit from fully featured ``ValidationError``\s (with a ``code`` name
  144. and a ``params`` dictionary).
  145. Raising multiple errors
  146. ~~~~~~~~~~~~~~~~~~~~~~~
  147. If you detect multiple errors during a cleaning method and wish to signal all
  148. of them to the form submitter, it is possible to pass a list of errors to the
  149. ``ValidationError`` constructor.
  150. As above, it is recommended to pass a list of ``ValidationError`` instances
  151. with ``code``\s and ``params`` but a list of strings will also work::
  152. # Good
  153. raise ValidationError([
  154. ValidationError(_('Error 1'), code='error1'),
  155. ValidationError(_('Error 2'), code='error2'),
  156. ])
  157. # Bad
  158. raise ValidationError([
  159. _('Error 1'),
  160. _('Error 2'),
  161. ])
  162. Using validation in practice
  163. ----------------------------
  164. The previous sections explained how validation works in general for forms.
  165. Since it can sometimes be easier to put things into place by seeing each
  166. feature in use, here are a series of small examples that use each of the
  167. previous features.
  168. .. _validators:
  169. Using validators
  170. ~~~~~~~~~~~~~~~~
  171. Django's form (and model) fields support use of simple utility functions and
  172. classes known as validators. A validator is merely a callable object or
  173. function that takes a value and simply returns nothing if the value is valid or
  174. raises a :exc:`~django.core.exceptions.ValidationError` if not. These can be
  175. passed to a field's constructor, via the field's ``validators`` argument, or
  176. defined on the :class:`~django.forms.Field` class itself with the
  177. ``default_validators`` attribute.
  178. Simple validators can be used to validate values inside the field, let's have
  179. a look at Django's ``SlugField``::
  180. from django.forms import CharField
  181. from django.core import validators
  182. class SlugField(CharField):
  183. default_validators = [validators.validate_slug]
  184. As you can see, ``SlugField`` is just a ``CharField`` with a customized
  185. validator that validates that submitted text obeys to some character rules.
  186. This can also be done on field definition so::
  187. slug = forms.SlugField()
  188. is equivalent to::
  189. slug = forms.CharField(validators=[validators.validate_slug])
  190. Common cases such as validating against an email or a regular expression can be
  191. handled using existing validator classes available in Django. For example,
  192. ``validators.validate_slug`` is an instance of
  193. a :class:`~django.core.validators.RegexValidator` constructed with the first
  194. argument being the pattern: ``^[-a-zA-Z0-9_]+$``. See the section on
  195. :doc:`writing validators </ref/validators>` to see a list of what is already
  196. available and for an example of how to write a validator.
  197. Form field default cleaning
  198. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  199. Let's firstly create a custom form field that validates its input is a string
  200. containing comma-separated email addresses. The full class looks like this::
  201. from django import forms
  202. from django.core.validators import validate_email
  203. class MultiEmailField(forms.Field):
  204. def to_python(self, value):
  205. "Normalize data to a list of strings."
  206. # Return an empty list if no input was given.
  207. if not value:
  208. return []
  209. return value.split(',')
  210. def validate(self, value):
  211. "Check if value consists only of valid emails."
  212. # Use the parent's handling of required fields, etc.
  213. super(MultiEmailField, self).validate(value)
  214. for email in value:
  215. validate_email(email)
  216. Every form that uses this field will have these methods run before anything
  217. else can be done with the field's data. This is cleaning that is specific to
  218. this type of field, regardless of how it is subsequently used.
  219. Let's create a simple ``ContactForm`` to demonstrate how you'd use this
  220. field::
  221. class ContactForm(forms.Form):
  222. subject = forms.CharField(max_length=100)
  223. message = forms.CharField()
  224. sender = forms.EmailField()
  225. recipients = MultiEmailField()
  226. cc_myself = forms.BooleanField(required=False)
  227. Simply use ``MultiEmailField`` like any other form field. When the
  228. ``is_valid()`` method is called on the form, the ``MultiEmailField.clean()``
  229. method will be run as part of the cleaning process and it will, in turn, call
  230. the custom ``to_python()`` and ``validate()`` methods.
  231. Cleaning a specific field attribute
  232. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  233. Continuing on from the previous example, suppose that in our ``ContactForm``,
  234. we want to make sure that the ``recipients`` field always contains the address
  235. ``"fred@example.com"``. This is validation that is specific to our form, so we
  236. don't want to put it into the general ``MultiEmailField`` class. Instead, we
  237. write a cleaning method that operates on the ``recipients`` field, like so::
  238. from django import forms
  239. class ContactForm(forms.Form):
  240. # Everything as before.
  241. ...
  242. def clean_recipients(self):
  243. data = self.cleaned_data['recipients']
  244. if "fred@example.com" not in data:
  245. raise forms.ValidationError("You have forgotten about Fred!")
  246. # Always return the cleaned data, whether you have changed it or
  247. # not.
  248. return data
  249. Sometimes you may want to add an error message to a particular field from the
  250. form's ``clean()`` method, in which case you can use
  251. :meth:`~django.forms.Form.add_error()`. Note that this won't always be
  252. appropriate and the more typical situation is to raise a ``ValidationError``
  253. from , which is turned into a form-wide error that is available through the
  254. :meth:`Form.non_field_errors() <django.forms.Form.non_field_errors>` method.
  255. Cleaning and validating fields that depend on each other
  256. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  257. .. method:: django.forms.Form.clean()
  258. Suppose we add another requirement to our contact form: if the ``cc_myself``
  259. field is ``True``, the ``subject`` must contain the word ``"help"``. We are
  260. performing validation on more than one field at a time, so the form's
  261. ``clean()`` method is a good spot to do this. Notice that we are talking about
  262. the ``clean()`` method on the form here, whereas earlier we were writing a
  263. ``clean()`` method on a field. It's important to keep the field and form
  264. difference clear when working out where to validate things. Fields are single
  265. data points, forms are a collection of fields.
  266. By the time the form's ``clean()`` method is called, all the individual field
  267. clean methods will have been run (the previous two sections), so
  268. ``self.cleaned_data`` will be populated with any data that has survived so
  269. far. So you also need to remember to allow for the fact that the fields you
  270. are wanting to validate might not have survived the initial individual field
  271. checks.
  272. There are two ways to report any errors from this step. Probably the most
  273. common method is to display the error at the top of the form. To create such
  274. an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
  275. example::
  276. from django import forms
  277. class ContactForm(forms.Form):
  278. # Everything as before.
  279. ...
  280. def clean(self):
  281. cleaned_data = super(ContactForm, self).clean()
  282. cc_myself = cleaned_data.get("cc_myself")
  283. subject = cleaned_data.get("subject")
  284. if cc_myself and subject:
  285. # Only do something if both fields are valid so far.
  286. if "help" not in subject:
  287. raise forms.ValidationError("Did not send for 'help' in "
  288. "the subject despite CC'ing yourself.")
  289. .. versionchanged:: 1.7
  290. In previous versions of Django, ``form.clean()`` was required to return
  291. a dictionary of ``cleaned_data``. This method may still return a dictionary
  292. of data to be used, but it's no longer required.
  293. In this code, if the validation error is raised, the form will display an
  294. error message at the top of the form (normally) describing the problem.
  295. Note that the call to ``super(ContactForm, self).clean()`` in the example code
  296. ensures that any validation logic in parent classes is maintained.
  297. The second approach might involve assigning the error message to one of the
  298. fields. In this case, let's assign an error message to both the "subject" and
  299. "cc_myself" rows in the form display. Be careful when doing this in practice,
  300. since it can lead to confusing form output. We're showing what is possible
  301. here and leaving it up to you and your designers to work out what works
  302. effectively in your particular situation. Our new code (replacing the previous
  303. sample) looks like this::
  304. from django import forms
  305. class ContactForm(forms.Form):
  306. # Everything as before.
  307. ...
  308. def clean(self):
  309. cleaned_data = super(ContactForm, self).clean()
  310. cc_myself = cleaned_data.get("cc_myself")
  311. subject = cleaned_data.get("subject")
  312. if cc_myself and subject and "help" not in subject:
  313. msg = "Must put 'help' in subject when cc'ing yourself."
  314. self.add_error('cc_myself', msg)
  315. self.add_error('subject', msg)
  316. The second argument of ``add_error()`` can be a simple string, or preferably
  317. an instance of ``ValidationError``. See :ref:`raising-validation-error` for
  318. more details. Note that ``add_error()`` automatically removes the field
  319. from ``cleaned_data``.