Question

Is it possible to have some of the new attribute only attributes used in HTML5, inside of WTForms?

Eg, say you want to create a TextField with placeholder="foo", required, and autofocus attributes. How would this be done in WTForms?

In html it would look like this: <input maxlength="256" name="q" value="" placeholder="foo" autofocus required>

Note that placeholder="foo" is easily done in WTForms. autofocus and required, because they have no value, are .. well, as far as i've seen, not supported in WTForms.

Can WTForms support this?

Was it helpful?

Solution

You'll probably need to create a custom widget.

Check out the docs on custom widgets.

OTHER TIPS

In WTForms 1.0, released yesterday, HTML5 compact syntax is now the default. Now you can do (in jinja):

{{ form.field(autofocus=true, required=true, placeholder="foo") }}

Note that in Jinja, the literal is true instead of True but if you were to try this in the python console you will need to use the python literal True for this to work.

In WTForms 0.6.x, which used XHTML as the default output, you could do e.g.

{{ form.field(autofocus="autofocus", required="required", placeholder="foo" }}

This is the recommended way for representing boolean attributes in XHTML, and this happens to still be 100% valid HTML5 and completely equivalent, though the HTML generated is a bit more verbose.

I'm new with WTForms but it seems to me that the solution could be improved instead of using :

{{ form.field(autofocus=true, required=true, placeholder="foo") }}

use :

{% if field.flags.required %}
   {{ field(autofocus=true, required=field.flags.required, placeholder="foo") }}
{% else %}
   {{ field(autofocus=true, placeholder="foo") }}
{% endif %}

WTForms seems not to handle correctly required=false for 100% HTML5 and sets in the HTML an attr required="False" instead of removing the attr. Could this be improved in next version of WTForms?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top