WTForms Can I add a placeholder attribute when I init a field?

Kit Ho picture Kit Ho · Mar 17, 2012 · Viewed 43k times · Source

I want to add a placeholder attribute on to the field in WTForms. How can I do it?

abc = TextField('abc', validators=[Required(), Length(min=3, max=30)], placeholder="test")

The above code is not valid

How can I add a placeholder attribute with value?

Answer

Crast picture Crast · Mar 20, 2012

Updated for WTForms 2.1

You can now as of WTForms 2.1 (December 2015) set rendering keywords by using the render_kw= parameter to the field constructor.

So the field would look like:

abc = StringField('abc', [InputRequired()], render_kw={"placeholder": "test"})

Note while this is possible; it does start to bridge the line between code and presentation; so use it wisely!


(Old answer, still true for versions older than WTForms 2.1)

placeholder is not supported in the Python constructor in WTforms 2.0.x and below.

However, you can do this easily in your template:

{{ form.abc(placeholder="test") }}