[Flask] Default/Disabled choices in WTForms SelectField?

Anthony Ford ford.anthonyj at gmail.com
Thu May 19 15:16:51 EDT 2016

Hey Alex,

So the you can pass the default  via the keyword argument `default`. In
something like a SelectField, you just give it the same value as the
default choice (i.e. if you have a choice that's `(1,"My First Choice")`,
default would be `default=1`).

Now for disabled, you have to slightly abuse HTML. From what I remember, as
long as "disabled" is present within the tag, most browsers will read that
as disabled. Its supposed to be a boolean field, and supposedly setting it
to a null string or "false" should enable the field, but that's never
worked for me. You can assign "disabled" a value, which should cause it to
evaluate as true for all browsers. Something as simple as
disabled="disabled in your input field should be enough to cause the
browser to render it as disabled.

So WTForms will accept keyword arguments to render to the field when
generating the html. So in your template, you can feed it
`disabled="disabled"` when you print your field (i.e.
myform.selfield(disabled="disabled")). Or if you want all instances of this
form to have that field disabled by default, and your JS will enable it
later, you can use the `render_kw` argument in the SelectField when you
declare your form.

All of this is listed in the WTForms docs (
It's part of the Field base class. Hope this helps!

I put together a Gist with an example:

Anthony Ford,
ford.anthonyj at gmail.com

On Thu, May 19, 2016 at 1:04 PM, Alex Hall <ahall at autodist.com> wrote:

> Hi all,
> This is perhaps more of a WTForms question, but I'm hoping people here
> will know how to do this in Flask-WTF.
> I have three select lists, and until the user clicks them, they're all
> blank. I want to have them each show an unselectable option to indicate
> that they exist, something like
> option value="1" default disabled>Please choose an option</option
> I can't find a way to do this in WTF though. I found one forum that said
> you can pass a "default=" argument to the SelectField constructor, but I
> don't see that in the official documentation. Plus, that doesn't tell me
> how to make the same item disabled, or if what goes after the equals sign
> is an index or an element in the choices list of values.
> Thanks for any suggestions. If this is doable, will it work the same way
> on SelectMultipleField items as well?
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160519/cbdc042a/attachment.html>

More information about the Flask mailing list