Creating custom form fields
Sometimes, the needs of the project outweigh the options that are provided to us. If a field class is not available by default, we have two options: create our own or use a third-party package where someone else has already written a field class for us.
Continuing with the same ContactForm
class, we will demonstrate the differences between validation mechanisms by building a MultipleEmailField
. This will be a single field, accepting a single string of emails, all separated by commas. Each email item will then be checked independently to see whether it is in a valid email string format. We will use the same validate_email()
function as we did before to enforce this constraint.
Field class – Field
Django provides a class called Field
found in the django.forms.fields
library, used to construct custom field classes. Any of the options and methods found in this class can be overwritten as needed. For example, overriding the def __init__()
method...