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.         ValidationError(_('Error 1'), code='error1'),
    
  199.         ValidationError(_('Error 2'), code='error2'),
    
  200.     ])
    
  201. 
    
  202.     # Bad
    
  203.     raise ValidationError([
    
  204.         _('Error 1'),
    
  205.         _('Error 2'),
    
  206.     ])
    
  207. 
    
  208. Using validation in practice
    
  209. ============================
    
  210. 
    
  211. The previous sections explained how validation works in general for forms.
    
  212. Since it can sometimes be easier to put things into place by seeing each
    
  213. feature in use, here are a series of small examples that use each of the
    
  214. previous features.
    
  215. 
    
  216. .. _validators:
    
  217. 
    
  218. Using validators
    
  219. ----------------
    
  220. 
    
  221. Django's form (and model) fields support use of utility functions and classes
    
  222. known as validators. A validator is a callable object or function that takes a
    
  223. value and returns nothing if the value is valid or raises a
    
  224. :exc:`~django.core.exceptions.ValidationError` if not. These can be passed to a
    
  225. field's constructor, via the field's ``validators`` argument, or defined on the
    
  226. :class:`~django.forms.Field` class itself with the ``default_validators``
    
  227. attribute.
    
  228. 
    
  229. Validators can be used to validate values inside the field, let's have a look
    
  230. at Django's ``SlugField``::
    
  231. 
    
  232.     from django.core import validators
    
  233.     from django.forms import CharField
    
  234. 
    
  235.     class SlugField(CharField):
    
  236.         default_validators = [validators.validate_slug]
    
  237. 
    
  238. As you can see, ``SlugField`` is a ``CharField`` with a customized validator
    
  239. that validates that submitted text obeys to some character rules. This can also
    
  240. be done on field definition so::
    
  241. 
    
  242.     slug = forms.SlugField()
    
  243. 
    
  244. is equivalent to::
    
  245. 
    
  246.     slug = forms.CharField(validators=[validators.validate_slug])
    
  247. 
    
  248. Common cases such as validating against an email or a regular expression can be
    
  249. handled using existing validator classes available in Django. For example,
    
  250. ``validators.validate_slug`` is an instance of
    
  251. a :class:`~django.core.validators.RegexValidator` constructed with the first
    
  252. argument being the pattern: ``^[-a-zA-Z0-9_]+$``. See the section on
    
  253. :doc:`writing validators </ref/validators>` to see a list of what is already
    
  254. available and for an example of how to write a validator.
    
  255. 
    
  256. Form field default cleaning
    
  257. ---------------------------
    
  258. 
    
  259. Let's first create a custom form field that validates its input is a string
    
  260. containing comma-separated email addresses. The full class looks like this::
    
  261. 
    
  262.     from django import forms
    
  263.     from django.core.validators import validate_email
    
  264. 
    
  265.     class MultiEmailField(forms.Field):
    
  266.         def to_python(self, value):
    
  267.             """Normalize data to a list of strings."""
    
  268.             # Return an empty list if no input was given.
    
  269.             if not value:
    
  270.                 return []
    
  271.             return value.split(',')
    
  272. 
    
  273.         def validate(self, value):
    
  274.             """Check if value consists only of valid emails."""
    
  275.             # Use the parent's handling of required fields, etc.
    
  276.             super().validate(value)
    
  277.             for email in value:
    
  278.                 validate_email(email)
    
  279. 
    
  280. Every form that uses this field will have these methods run before anything
    
  281. else can be done with the field's data. This is cleaning that is specific to
    
  282. this type of field, regardless of how it is subsequently used.
    
  283. 
    
  284. Let's create a ``ContactForm`` to demonstrate how you'd use this field::
    
  285. 
    
  286.     class ContactForm(forms.Form):
    
  287.         subject = forms.CharField(max_length=100)
    
  288.         message = forms.CharField()
    
  289.         sender = forms.EmailField()
    
  290.         recipients = MultiEmailField()
    
  291.         cc_myself = forms.BooleanField(required=False)
    
  292. 
    
  293. Use ``MultiEmailField`` like any other form field. When the ``is_valid()``
    
  294. method is called on the form, the ``MultiEmailField.clean()`` method will be
    
  295. run as part of the cleaning process and it will, in turn, call the custom
    
  296. ``to_python()`` and ``validate()`` methods.
    
  297. 
    
  298. Cleaning a specific field attribute
    
  299. -----------------------------------
    
  300. 
    
  301. Continuing on from the previous example, suppose that in our ``ContactForm``,
    
  302. we want to make sure that the ``recipients`` field always contains the address
    
  303. ``"[email protected]"``. This is validation that is specific to our form, so we
    
  304. don't want to put it into the general ``MultiEmailField`` class. Instead, we
    
  305. write a cleaning method that operates on the ``recipients`` field, like so::
    
  306. 
    
  307.     from django import forms
    
  308.     from django.core.exceptions import ValidationError
    
  309. 
    
  310.     class ContactForm(forms.Form):
    
  311.         # Everything as before.
    
  312.         ...
    
  313. 
    
  314.         def clean_recipients(self):
    
  315.             data = self.cleaned_data['recipients']
    
  316.             if "[email protected]" not in data:
    
  317.                 raise ValidationError("You have forgotten about Fred!")
    
  318. 
    
  319.             # Always return a value to use as the new cleaned data, even if
    
  320.             # this method didn't change it.
    
  321.             return data
    
  322. 
    
  323. .. _validating-fields-with-clean:
    
  324. 
    
  325. Cleaning and validating fields that depend on each other
    
  326. --------------------------------------------------------
    
  327. 
    
  328. Suppose we add another requirement to our contact form: if the ``cc_myself``
    
  329. field is ``True``, the ``subject`` must contain the word ``"help"``. We are
    
  330. performing validation on more than one field at a time, so the form's
    
  331. :meth:`~Form.clean()` method is a good spot to do this. Notice that we are
    
  332. talking about the ``clean()`` method on the form here, whereas earlier we were
    
  333. writing a ``clean()`` method on a field. It's important to keep the field and
    
  334. form difference clear when working out where to validate things. Fields are
    
  335. single data points, forms are a collection of fields.
    
  336. 
    
  337. By the time the form's ``clean()`` method is called, all the individual field
    
  338. clean methods will have been run (the previous two sections), so
    
  339. ``self.cleaned_data`` will be populated with any data that has survived so
    
  340. far. So you also need to remember to allow for the fact that the fields you
    
  341. are wanting to validate might not have survived the initial individual field
    
  342. checks.
    
  343. 
    
  344. There are two ways to report any errors from this step. Probably the most
    
  345. common method is to display the error at the top of the form. To create such
    
  346. an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
    
  347. example::
    
  348. 
    
  349.     from django import forms
    
  350.     from django.core.exceptions import ValidationError
    
  351. 
    
  352.     class ContactForm(forms.Form):
    
  353.         # Everything as before.
    
  354.         ...
    
  355. 
    
  356.         def clean(self):
    
  357.             cleaned_data = super().clean()
    
  358.             cc_myself = cleaned_data.get("cc_myself")
    
  359.             subject = cleaned_data.get("subject")
    
  360. 
    
  361.             if cc_myself and subject:
    
  362.                 # Only do something if both fields are valid so far.
    
  363.                 if "help" not in subject:
    
  364.                     raise ValidationError(
    
  365.                         "Did not send for 'help' in the subject despite "
    
  366.                         "CC'ing yourself."
    
  367.                     )
    
  368. 
    
  369. In this code, if the validation error is raised, the form will display an
    
  370. error message at the top of the form (normally) describing the problem. Such
    
  371. errors are non-field errors, which are displayed in the template with
    
  372. ``{{ form.non_field_errors }}``.
    
  373. 
    
  374. The call to ``super().clean()`` in the example code ensures that any validation
    
  375. logic in parent classes is maintained. If your form inherits another that
    
  376. doesn't return a ``cleaned_data`` dictionary in its ``clean()`` method (doing
    
  377. so is optional), then don't assign ``cleaned_data`` to the result of the
    
  378. ``super()`` call and use ``self.cleaned_data`` instead::
    
  379. 
    
  380.     def clean(self):
    
  381.         super().clean()
    
  382.         cc_myself = self.cleaned_data.get("cc_myself")
    
  383.         ...
    
  384. 
    
  385. The second approach for reporting validation errors might involve assigning the
    
  386. error message to one of the fields. In this case, let's assign an error message
    
  387. to both the "subject" and "cc_myself" rows in the form display. Be careful when
    
  388. doing this in practice, since it can lead to confusing form output. We're
    
  389. showing what is possible here and leaving it up to you and your designers to
    
  390. work out what works effectively in your particular situation. Our new code
    
  391. (replacing the previous sample) looks like this::
    
  392. 
    
  393.     from django import forms
    
  394. 
    
  395.     class ContactForm(forms.Form):
    
  396.         # Everything as before.
    
  397.         ...
    
  398. 
    
  399.         def clean(self):
    
  400.             cleaned_data = super().clean()
    
  401.             cc_myself = cleaned_data.get("cc_myself")
    
  402.             subject = cleaned_data.get("subject")
    
  403. 
    
  404.             if cc_myself and subject and "help" not in subject:
    
  405.                 msg = "Must put 'help' in subject when cc'ing yourself."
    
  406.                 self.add_error('cc_myself', msg)
    
  407.                 self.add_error('subject', msg)
    
  408. 
    
  409. The second argument of ``add_error()`` can be a string, or preferably an
    
  410. instance of ``ValidationError``. See :ref:`raising-validation-error` for more
    
  411. details. Note that ``add_error()`` automatically removes the field from
    
  412. ``cleaned_data``.