Flask-wtf: Using a kwarg to set the initial value for a field

697 views Asked by At

I'd like to use a kwarg to set the initial value of a form field. I've previously done something similar to:

from wtforms import Form
from wtforms.fields import StringField

class BasicForm(Form):
    inputField = StringField("Name")

basic_form_kwargs = {"inputField" : "Example"}
basic_form = BasicForm(**basic_form_kwargs)
print basic_form.inputField
#<input id="inputField" name="inputField" type="text" value="Example">

This code works as I expect. The value attribute is set to "Example". However when I start using FormFields it doesn't work as I expect.

from wtforms import Form
from wtforms.fields import StringField

class ChildForm(Form):
    inputField = StringField("Name")
class ParentForm(Form):
    childWrapper = FormField(ChildForm)

complex_form_kwargs = {"childWrapper-inputField" : "Example"}
complex_form = ParentForm(**complex_form_kwargs)
print complex_form.childWrapper.inputField
#<input id="childWrapper-inputField" name="childWrapper-inputField" type="text" value="">

What kwarg needs to be passed so that I can set the value of inputField when using FormFields?

1

There are 1 answers

0
junnytony On BEST ANSWER

Just like you passed a dict into the parent level form, you need to pass a dict into the child form like this:

kwargs = {"childWrapper": {"inputFIeld": "Example2"}}
form = ParentForm(**kwargs)