If I set the default value during construction of the field, all works as expected:
my_field = StringField("My Field: ", default="default value", validators=[Optional(), Length(0, 255)])
However, if I try to set it programmatically, it has no effect. I've tried by modifying the __init__
method like so:
class MyForm(FlaskForm):
my_field = StringField("My Field: ", validators=[Optional(), Length(0, 255)])
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.my_field.default = "set default from init" # doesn't work
This does not set the default value. How can I do this programatically (because the value is dynamic based on a database query, and if I do this outside of __init__
then it does not get the most current value)?
Relevant versions from my requirements.txt
:
Flask==0.12
Flask-WTF==0.14.2
WTForms==2.1
Also, I'm running Python 3.6 if that matters.
Alternatively, I'm fine with a solution that enables me to set the value data for this field on initial form load when adding a new record (same behavior as default value being specified in constructor) but this same form is also used for editing so I would not want it changing object data that is already saved/stored on edit.
form.field.choices
after creating the form, but not if I did it inside the form's__init__
method. Perhaps you could ask a separate question for this, showing how you're populating the choices? Thanks for spotting the Foo typo in the other answer. – Astrix