text:  - simple helpers that can be
  reused easily. Validators are simple functions (or callables) that take a single
  argument and raise
  ValidationError on invalid input. Validators are run
  after the field’s
  to_python and
  validate methods have been called.
  Validation of a form is split into several steps, which can be customized or overridden:
  The
  to_python()method on a
  Field to a correct datatype and raises
  ValidationErroron any error. This method does not return anything and shouldn’t alter the value. You should override it to handle validation logic that you can’t or don’t want to put in a validator.
  The
  run_validators()method on a
  Fieldruns all of the field’s validators and aggregates all the errors into a single
  ValidationError. You shouldn’t need to override this method.
  The
  clean()method on a
  Fieldsubclass is responsible for running
  to_python(),
  validate(), and
  run_validators()in the correct order and propagating their errors. If, at any time, any of the methods raise
  ValidationError, the validation stops and that error is raised. This method returns the clean data, which is then inserted into the
  cleaned_datadictionary of the form.
  The
  clean_<fieldname>()method is called on a form subclass – where
  <fieldname>is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in
  self.cleaned_dataand remember that it will be a Python object at this point, not the original string submitted in the form (it will be in
  cleaned_databecause the general field
  clean()method, above, has already cleaned the data once).
  For example, if you wanted to validate that the contents of a
  CharFieldcalled
  serialnumberwas unique,
  clean_serialnumber()would be the right place to do this. You don’t need a specific field (it’s just.
  Note that any errors raised by your
  Form.clean()override will not be associated with any field in particular. They go into a special “field” (called
  __all__), which you can access via the
  non_field_errors()method if you need to. If you want to attach errors to a specific field in the form, you need to call
  add_error().
  Also note that there are special considerations when overriding the
  clean()method of a
  ModelFormsubclass. (see the ModelForm documentation for more information)
  These methods are run in the order given above, one field at a time. That is,
  for each field in the form (in the order they are declared in the form
  definition), the
  Field.clean() method (or its override) is run, then
  clean_<fieldname>(). Finally, once those two methods are run for every
  field, the
  Form.clean() method, or its override, is executed whether
  or not the previous methods have raised errors.
  Examples of each of these methods are provided below.
  As mentioned, any of these methods can raise a
  ValidationError. For any
  field, if the
  Field.clean() method raises a
  ValidationError, any
  field-specific cleaning method is not called. However, the cleaning methods
  for all remaining fields are still executed.'), ])
  Using validation in practice¶
  The previous sections explained how validation works in general for forms. Since it can sometimes be easier to put things into place by seeing each feature in use, here are a series of small examples that use each of the previous features.
  Using validators¶
  Django’s form (and model) fields support use of simple utility functions and
  classes known as validators. A validator is merely a callable object or
  function that takes a value and simply returns nothing if the value is valid or
  raises a
  ValidationError if not..core import validators from django.forms import CharField]) create a custom form field that validates its input is a string containing comma-separated email addresses. The full class looks like this:
  from django import forms from django.core.validators import validate_email class MultiEmailField(forms.Field): def to_python(self, value): """Normalize data to a list of strings.""" # Return an empty list if no input was given. if not value: return [] return value.split(',') def validate(self, value): """Check if value consists only of valid emails.""" # Use the parent's handling of required fields, etc. super().validate(value) for email in value: validate_email(email)
  Every form that uses this field will have these methods run before anything else can be done with the field’s data. This is cleaning that is specific to this type of field, regardless of how it is subsequently used.
  Let’s create a simple
  ContactForm to demonstrate how you’d use this
  field:
  class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() recipients = MultiEmailField() cc_myself = forms.BooleanField(required=False)
  Simply use
  MultiEmailField like any other form field. When the
  is_valid() method is called on the form, the
  MultiEmailField.clean()
  method will be run as part of the cleaning process and it will, in turn, call
  the custom
  to_python() and
  validate() methods.
  Cleaning a specific field attribute¶
  Continuing on from the previous example, suppose that in our
  ContactForm,
  we want to make sure that the
  recipients field always contains the address
  "fred@example.com". This is validation that is specific to our form, so we
  don’t want to put it into the general
  MultiEmailField class. Instead, we
  write a cleaning method that operates on the
  recipients field, like so:
  from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean_recipients(self): data = self.cleaned_data['recipients'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") # Always return a value to use as the new cleaned data, even if # this method didn't change it. return data
  Cleaning and validating fields that depend on each other¶
  Suppose we add another requirement to our contact form: if the
  cc_myself
  field is
  True, the
  subject must contain the word
  "help". We are
  performing validation on more than one field at a time, so the form’s
  clean() method is a good spot to do this. Notice that we are
  talking about the
  clean() method on the form here, whereas earlier we were
  writing a
  clean() method on a field. It’s important to keep the field and
  form difference clear when working out where to validate things. Fields are
  single data points, forms are a collection of fields.
  By the time the form’s
  clean() method is called, all the individual field
  clean methods will have been run (the previous two sections), so
  self.cleaned_data will be populated with any data that has survived so
  far. So you also need to remember to allow for the fact that the fields you
  are wanting to validate might not have survived the initial individual field
  checks.
  There are two ways to report any errors from this step. Probably the most
  common method is to display the error at the top of the form. To create such
  an error, you can raise a
  ValidationError from the
  clean() method. For
  example:
  from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise forms.ValidationError( "Did not send for 'help' in the subject despite " "CC'ing yourself." )
  In this code, if the validation error is raised, the form will display an error message at the top of the form (normally) describing the problem. might involve assigning the error message to one of the fields. In this case, let’s assign an error message to both the “subject” and “cc_myself” rows in the form display. Be careful when doing this in practice, since it can lead to confusing form output. We’re showing what is possible here and leaving it up to you and your designers to work out what works effectively in your particular situation. Our new code (replacing the previous sample) looks like this: simple string, or preferably
  an instance of
  ValidationError. See Raising ValidationError for
  more details. Note that
  add_error() automatically removes the field
  from
  cleaned_data.