Custom field validation and cleaning
We have seen how a Django form converts values from an HTTP request, which are strings, into Python objects. In a non-custom Django form, the target type is dependent on the field class. For example, the Python type derived from IntegerField
is int
, and string values are given to us verbatim, as the user entered them. But, we can also implement methods on our Form
class to alter the output values from our fields in any way we choose. This allows us to clean or filter the user’s input data to fit what we expect better. We could round an integer to the nearest multiple of 10 so that it fits into a batch size for ordering specific items. Or, we could transform an email address into lowercase so that the data is consistent for searching.
We can also implement some custom validators. We’ll look at a couple of different ways of validating fields: by writing a custom validator, and by writing a custom clean
method for the field. Each method...