Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms... html, autofocus?

Tags:

python

wtforms

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?

like image 438
Lee Olayvar Avatar asked Jul 27 '10 03:07

Lee Olayvar


2 Answers

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.

like image 98
Crast Avatar answered Nov 11 '22 10:11

Crast


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?

like image 33
Frank Avatar answered Nov 11 '22 10:11

Frank