Creating a common form set
An application can have many forms, depending on the design and purpose. Some of these forms will have common fields with common validators. You might think, “Why not have common form parts and then reuse them as and when needed?” In this recipe, we will see that this is certainly possible with the class structure for forms’ definition provided by WTForms.
How to do it...
In our catalog application, we can have two forms, one each for the Product
and Category
models. These forms will have a common field called Name
. We can create a common form for this field, and then the separate forms for the Product
and Category
models can use this form, instead of having a Name
field in each of them.
This can be implemented as follows in models.py
:
class NameForm(FlaskForm): name = StringField('Name', validators=[InputRequired()]) class ProductForm(NameForm): ...