2
0

validation.txt 17 KB

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