pdoherty926
pdoherty926

Reputation: 10409

How can I dynamically set a default value for a WTForms FormField?

Given the following two WTFforms:

class NestedForm(FlaskForm):
    note = StringField('Note', validators=[DataRequired()])
    some_id = StringField('Some ID', validators=[DataRequired()])

class Form(FlaskForm):
    id = HiddenField('ID')
    nested_forms = FieldList(
        FormField(NestedForm),
        min_entries=1,
    )

How can I dynamically set the value of some_id? For instance, from within a Flask view, if a value for some_id hasn't been provided.

I have tried setting the value using the following:

form.nested_forms[0].some_id = "some_contextual_default_value"
form.nested_form[0].data['some_id'] = "some_contextual_default_value"

... which don't seem to do anything. The form validation continues to fail with an error saying that the required field (some_id) is missing.

Upvotes: 2

Views: 813

Answers (1)

noslenkwah
noslenkwah

Reputation: 1744

Use the data attribute.

form.nested_forms[0].some_id.data = "some_contextual_default_value"

Upvotes: 2

Related Questions