Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set a default value for a WTForms SelectField?

When attempting to set the default value of a SelectField with WTForms, I pass in value to the 'default' parameter like so.

class TestForm(Form):   test_field = SelectField("Test: ", choices=[(1, "Abc"), (2, "Def")], default=2) 

I have also tried the following.

class TestForm(Form):   test_field = SelectField("Test: ", choices=[(1, "Abc"), (2, "Def")], default=(2, "Def")) 

Neither set the default selected field to "Def." This works for other kinds of Fields such as TextField. How do you set the default value for a SelectField?'

like image 783
jan Avatar asked Aug 23 '12 20:08

jan


People also ask

What is WTForms in Python?

WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.

What is the default value of a form field?

A reasonable default is set by the form, and you shouldn’t need to set this manually. default– The default value to assign to the field, if no form or object input is provided.

Why is selectmultiplefield not working in wt forms?

The only explanation for it not working can be that you are running an older version of WTForms, it worked for me on 1.0.1 Note that for a SelectMultipleField, the default has to be a list, i.e.: default= [2]. There are a few ways to do this.

What is the use of wtforms select field?

class wtforms.fields. SelectField(default field arguments, choices=[], coerce=unicode, option_widget=None, validate_choice=True)[source]¶ Select fields take a choicesparameter which is a list of (value,label)pairs. It can also be a list of only values, in which case the value is used as the label.

What is the default format of datetimefield in wtforms?

class wtforms.fields.html5. DateTimeField(default field arguments, format='%Y-%m-%d %H:%M:%S')[source]¶ Represents an <inputtype="datetime">.


2 Answers

I believe this problem is caused by the Field's data attribute overriding the default with something that WTForms doesn't understand (e.g. a DB model object -- it expects an int). This would happen if you have populated your form in the constructor like so:

form = PostForm(obj=post) 

the solution is to manually set the data attribute after the form has been populated:

form = PostForm(obj=post) form.category.data = (post.category.id                       if page.category                       else 0) # I make 0 my default 
like image 105
Elliott Avatar answered Sep 29 '22 02:09

Elliott


The first way you posted is correct, and it works for me. The only explanation for it not working can be that you are running an older version of WTForms, it worked for me on 1.0.1

like image 26
sp. Avatar answered Sep 29 '22 02:09

sp.