'Setting data attributes on a WTForms field
I want to add "data-" attributes to a form field for integration with Bootstrap. I tried the following in a template:
{{ form.test(data-toggle="toggle", data-size="mini", data-on="Yes", data-off="No", type="checkbox")}}
and got this error:
TemplateSyntaxError: expected token ',', got '='
Why did I get this error and how do I fix it?
Solution 1:[1]
You need to use valid Python names as the variable names. Therefore names like "data-toggle" are invalid because they have a "-" in them. Change the names to use underscores, like "data_toggle". WTForms automatically converts "_" to "-" for keywords it doesn't recognize.
{{ form.test(data_size="mini") }}
You can also use dict unpacking to pass keyword arguments with keys that aren't valid variables.
{{ form.name(**{"data-size": "mini"}) }}
Rather than setting the attributes when rendering, you can set the default attributes for the field with render_kw.
class ExampleForm(Form):
name = StringField(render_kw={"data-size": "mini"})
Solution 2:[2]
When creating a form add any data-* fields as a render_kw dictionary in the field definition. As follows in this example using Knockout:
class ScheduledReportForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()], render_kw={'data-bind':'value: name'})
submit = SubmitField('Submit')
Solution 3:[3]
As davidism explained, names like "data-toggle" aren't valid.
However, davidism's solution didn't work for me, WTFForm didn't convert '_' to '-'.
Maybe my version of WTFForms is too old (Flask-WTF==0.8.2 WTForms==1.0.2).
Alternatively, you can pass the HTML attributes that contain invalid syntax as an ad-hoc dictionary.
{{ form.test(type="checkbox", **{'data-toggle':'toggle', 'data-size'='mini', data-on="Yes"} )}}
Reference: http://flask.pocoo.org/snippets/107/
Solution 4:[4]
If you want to add an attribute like "disabled" or "readonly" then you can do it like this
{{ form.test(class_="input", readonly="readonly") }}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Martlark |
| Solution 3 | Patrick Cullen |
| Solution 4 | FineJ |
