Creating custom fields and validations
Apart from providing a bunch of fields and validations, Flask and WTForms also provide you with the flexibility to create custom fields and validations. Sometimes, we might need to parse some form of data that cannot be processed using the available current fields. In such cases, we can implement our own fields.
How to do it...
In our catalog application, we used SelectField
for the category, and we populated the values for this field in our create_product()
method on a GET
request by querying the Category
model. It would be much more convenient if we did not concern ourselves with this and the population of this field took care of itself.
Now, let’s implement a custom field to do this in models.py
:
class CategoryField(SelectField): def iter_choices(self): categories = [(c.id, c.name) for c in Category...