Select field in the form that is a part of FieldList loses its choices parameter when rendered in HTML.
Here is how the forms are set up:
class InvoiceLineForm(Form):
prod_id = SelectField('Product', coerce=int, validate_choice=False)
class InvoiceForm(FlaskForm):
cus_id = SelectField('Customer', choices=[])
line_forms = FieldList(FormField(InvoiceLineForm))
submit = SubmitField('Submit Update')
Here is the view:
def update_invoice(inv_id):
invoice = Invoice.get_by_id(inv_id) #Invoice values, including a list of dicts, called line_items
form = InvoiceForm()
if request.method == 'GET':
cus_dict = function() #function returns customers {id:name, id:name...}
form.cus_id.choices = [item for item in cus_dict.items()]
form.cus_id.default = invoice.cus_id
form.process()
#Set up lineitems
for line_item in invoice.line_items:
item_form = InvoiceLineForm()
item_form.prod_id.choices = [(-1,'---'), (-2, '+++')] # Dummy list
form.line_forms.append_entry(item_form)
return render_template('invoice_create.html', form = form)
And here is the HTML, styled with bootstrap 5
<div class="form-group">
{{ form.cus_id.label(class = "form-control-label") }}
{{ form.cus_id(class = "form-control")}}
</div>
<div class="form-group">
{% for line_form in form.line_forms %}
{{ line_form.prod_id.label(class = "form-control-label") }}
{{ line_form.prod_id(class = "form-control")}}
{% endfor %}
</div>
The top Select Field works like a charm, but the select field that is nested in the Field List has no choices when HTML is rendered. The select field is there, but it is empty. Using wtforms.Form vs flask_wtf.FlaskForm seems to make no difference. Calling process method on the nested form does not help either. I'm at the end of my wits here...
Turned out, choices list gets cleared by append_form method. Simply assigning values to this list after append solves the issue: