Creating a custom widget
Just like we can create custom fields and validators, we can also create custom widgets. These widgets allow us to control how our fields will look on the frontend. Each field type has a widget associated with it, and WTForms, by itself, provides a lot of basic and HTML5 widgets. In this recipe, to understand how to write a custom widget, we will convert our custom selection field for Category
into a radio field. I agree with those of you who would argue that we can directly use the radio field provided by WTForms. Here, we are just trying to understand how to do it ourselves.
Information
The widgets provided by default by WTForms can be found at https://wtforms.readthedocs.io/en/3.0.x/widgets/.
How to do it...
In our previous recipe, we created CategoryField
. This field used the Select
widget, which was provided by the Select
superclass. Let’s replace the Select
widget with a radio input in models.py
:
from wtforms.widgets import html_params...