How do you set a default value for a WTForms SelectField?
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
Setting default value after initialization in SelectField flask-WTForms
Once an instance of the form is created, the data is bound. Changing the default after that doesn't do anything. The reason changing choices
works is because it affects validation, which doesn't run until validate
is called.
Pass default data to the form constructor, and it will be used if no form data was passed. The default will be rendered the first time, then posted the second time if the user doesn't change the value.
form = AddressForm(request.form, country='US')
(If you're using Flask-WTF's Form
you can leave out the request.form
part.)
Set default in WTForms SelectField from Flask app config?
You need to check the consistence of the types of the variables you want to set.
For that, in your SelectField
, use the parameter coerce
.
If the variable app.config['PAGE_SIZE']
is an int
, you want to declare your form field like so :
page_size = SelectField('Entries/page',
choices=[(10, "10"), (25, "25"), (50, "50"), (100, "100")],
default=25,
coerce=int)
Setting a default value in the selectfield, using wtforms and flask
If you want set default value to render page with form you can create own form or set value:
class Product(Form):
product = TextField('name')
category = SelectField('category', choices=[(1,'one'),(2,'two')])
# create instance with predefined value:
form1 = Product(category=2)
# form1.product == <input id="product" name="product" type="text" value="">
# form1.category == <select id="category" name="category">
# <option value="1">one</option>
# <option selected value="2">two</option>
# </select>
# from1.product.data == None
# form1.category.data == 2
# create own form if it need many times:
Product2 = type('Product2', (Product,), {
'category': SelectField('category', default=2, choices=[(1,'one'),(2,'two')])
})
form2 = Product2()
# form2.product == <input id="product" name="product" type="text" value="">
# form2.category == <select id="category" name="category">
# <option value="1">one</option>
# <option selected value="2">two</option>
# </select>
# from2.product.data == None
# form2.category.data == 2
If you want set default form data on request:
with app.test_request_context(method='POST'):
form = Product(request.form)
# form5.category.data == None
form = Product(request.form, category=2)
# form5.category.data == 2
with app.test_request_context(method='POST', data={'category': 1}):
form = Product(request.form)
# form5.category.data == 1
form = Product(request.form, category=2)
# form5.category.data == 1
Flask WTForms Dynamic Default Value
This is how I like to handle dynamic form building
def buildWeightForm(last_weight):
class weight(FlaskForm):
weight = StringField('Enter your weight', default=last_weight, validators=[DataRequired()])
submit = SubmitField('Submit')
return weight()
For your 2nd question, if you're getting an error doing this
StringField('Enter your weight', validators=[DataRequired()], default=get_last_weight())
Try the following (removing your parentheses from your function call):
StringField('Enter your weight', validators=[DataRequired()], default=get_last_weight)
Related Topics
Why Is 'Object' an Instance of 'Type' and 'Type' an Instance of 'Object'
What Is the Best Approach to Change Primary Keys in an Existing Django App
Unicodeencodeerror: 'Ascii' Codec Can't Encode Character at Special Name
Write() Versus Writelines() and Concatenated Strings
How to One Hot Encode Variant Length Features
Selenium Python Error: Element Could Not Be Scrolled into View
How to Enable Pan and Zoom in a Qgraphicsview
How to Merge Multiple Lists into One List in Python
Python: Fastest Way to Create a List of N Lists
How to Get a List of All Indices of Repeated Elements in a Numpy Array
Import Script from a Parent Directory
Open Cv Error: (-215) Scn == 3 || Scn == 4 in Function Cvtcolor
Python: Slicing a Multi-Dimensional Array
Print List of Lists in Separate Lines
Running Python Scripts with Xampp
How to Install Python Packages in Google's Colab
Tkinter: Mouse Drag a Window Without Borders, Eg. Overridedirect(1)