I want to use a FieldList
to build a form via WTForms. I have a list of strings such as: vehicles = ['car', 'truck', 'van']
I have constructed my form so that I have: vehicles = ['car', 'truck', 'van']
class VehicleForm(Form):
value = DecimalField()
class VehicleEntryForm(FlaskForm):
values = FieldList(
FormField(VehicleForm),
min_entries=len(vehicles))
submit = SubmitField('Submit')
I am rending using jinja as:
<form action="" method="post">
{{ form.hidden_tag() }}
{% for value in form.values %}
{{value.label}}{{value()}}
{% endfor %}
{{ form.submit() }}
</form>
This creates a form with generic labels as one would expect. The html for the form label comes out as:
...<label for="values-0-value">Value</label>...
...<label for="values-1-value">Value</label>...
...<label for="values-2-value">Value</label>...
The question is how can I update the label value on the backend using my list. I tried:
form = VehicleEntryForm()
ii = 0
for field in form.values:
field.label = labels[ii]
ii+=1
and then updated html/jinja to:
<form action="" method="post">
{{ form.hidden_tag() }}
{% for value in form.values %}
{{value.label}}{{value()}}
{% endfor %}
{{ form.submit() }}
</form>
However, this resulted in now having:
car<table id="values-0" label="car"><tr><th><label for="values-0-value">Value</label></th><td><input id="values-0-value" name="values-0-value" required type="text" value=""></td></tr></table>
truck<table id="values-1" label="truck"><tr><th><label for="values-1-value">Value</label></th><td><input id="values-1-value" name="values-1-value" required type="text" value=""></td></tr></table>
This gets me halfway there... but how do I get replace of the <label for="values-0-value">Value</label>
with <label for="values-0-value">Car</label>
?
Note: the vehicles
list comes from a model query, so can be variable in length... which is why I tried this (if it was always just same 3 things, I'd just type it in).
I am open to alternative approaches if FieldList and FormField are not the way to do it.
Using FieldList, new fields can be added using append_entry()
This function doesn't give an option to add a label, but it can be edited after being added in form.values.entries
.
vehicles = ['car', 'truck', 'van']
form = VehicleEntryForm()
for vehicle in vehicles:
form.values.append_entry(data='foo')
form.values.entries[-1].label.text = vehicle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.