similar to this question: Dynamic choices WTForms Flask SelectField

In my flask app I have a WTForm with several selectfields. I would like to dynamically assign the number of the selectfields and the choices of the selectfields.

class FormEntry(FlaskForm):
        selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')])


class MyForm(FlaskForm):
    form_entries = FieldList(FormField(FormEntry), min_entries=1)

An instance of a FormEntry is created and the choices are assigned:

my_entry = FormEntry()
my_entry.selectfield.choices =[('3', 'mychoice3'), ('4', 'mychoice4')]

However, when I create an instance of the Form with this entry, the choices are not my chosen choices but the default ones:

form_entries = [my_entry, my_entry]
form = MyForm(form_entries=form_entries)
for entry in form.form_entries:
    print(entry.selectfield.choices)

Print Output:

[('1', 'default_choice1'), ('2', 'default_choice2')]
[('1', 'default_choice1'), ('2', 'default_choice2')]

What went wrong and how can I assign the choices correctly?

1 Answers

0
Andrew Allen On Best Solutions

https://wtforms.readthedocs.io/en/stable/fields.html#wtforms.fields.SelectField

From the documentation (emphasis mine)

Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. Any inputted choices which are not in the given choices list will cause validation on the field to fail.

i.e don't have selectfield = SelectField('Name', coerce=int, choices=[('1', 'default_choice1'), ('2', 'default_choice2')] use selectfield = SelectField('Name', coerce=int) instead.