Using Flask-WTForms, how do I style my form section of the html?

In WTForms 2.1 I use extra_classes, like the line below:

1. The first way

{{ f.render_form_field(form.first_name, extra_classes='ourClasses') }}

or maybe in your case just like this:

{{ form.first_name, extra_classes='ourClasses' }}

We can also use the render_kw attribute on our form field like the second way below:

2. The second way

style={'class': 'ourClasses', 'style': 'width:50%; other_css_style;'}
first_name = StringField('First name',
                     validators=[InputRequired(),Length(1, 64)],
                     render_kw=style)

But I would prefer to use the first way.


WTForms fields can be called with attributes that will be set on the input they render. Pass the attributes you need for styling, JavaScript functionality, etc. to the fields, rather than just referencing the fields. The labels behave the same way, and can be accessed with field.label.

for, value, type, id, and name do not need to be passed, as they are handled automatically. There are some rules for handling special cases of attributes. If an attribute name is a Python keyword such as class, append an underscore: class_. Dashes are not valid Python names, so underscores between words are converted to dashes; data_toggle becomes data-toggle.

{{ form.first_name(class_='validate') }}
{{ form.first_name.label(class_='active') }}

{{ form.begins(class_='datepicker', length=50) }}

Note that neither of the linked methods need to be called directly, those docs just describe the behavior when calling the fields.