Creating a common forms set
An application can have loads of forms, depending on the design and purpose. Many of these forms will have common fields with common validators. Many of us might think, "Why not have common forms parts and then reuse them as and when needed?" This is very much 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 done as follows:
class NameForm(Form): name = TextField('Name', validators=[InputRequired()]) class ProductForm(NameForm): price = DecimalField('Price', validators=[ InputRequired(), NumberRange(min=Decimal('0.0')) ]) category = SelectField( 'Category', validators...