[英]Flask WTForms dynamic select field from list instead of db
I am attempting to create a dynamic drop down (SelectField) with WTForms.我正在尝试使用 WTForms 创建一个动态下拉列表(SelectField)。 I have read the documentation and have looked at quite a few answers on stack, and all of the examples involve iterating over a db query.
我已经阅读了文档并查看了很多关于堆栈的答案,并且所有示例都涉及迭代 db 查询。
I simply want to iterate over a list (that's generated from an external API call) to inject the SelectField choices.我只想遍历一个列表(从外部 API 调用生成)以注入 SelectField 选项。 For example:
例如:
class ToolForm(FlaskForm):
myField3 = SelectField(u'Select Account', choices=[], coerce=int)
@app.route("/test", methods=['GET', 'POST'])
def test():
form = ToolForm()
accounts5 = []
if request.method == 'POST':
if request.form['submit_button'] == 'Select Account':
#code that generates list called "accounts5"
acctchoices = [(c.id,c.name) for c in accounts5]
form.myField3.choices = acctchoices
return render_template('test.html', title='test', form=form, accounts5=accounts5)
And my relevant HTML looks like:我的相关 HTML 如下所示:
<div class="form-group">
{{ form.myField3.label(class="form-control-label") }} {% if form.myField3.errors %} {{
form.myField3(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for errors in form.myField3.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %} {{ form.myField3(class="form-control form-control-lg") }} {% endif %}
</div>
<form action="http://127.0.0.1:5000/test" method="post">
<input type="submit" class="btn btn-outline-info" name="submit_button" value="Select Account">
</form>
When I click "Select Account" I get an 'int' object has no attribute 'id'
error.当我单击“选择帐户”时,出现
'int' object has no attribute 'id'
错误。 I thought this might be a data type issue so I tried with a list of strings but to no avail.我认为这可能是数据类型问题,所以我尝试使用字符串列表但无济于事。
My question is, how can I populate my SelectField from a list?我的问题是,如何从列表中填充我的 SelectField?
When you GET
that route it will load a form that is generic and render it to the page, without any myField3
choices having been set or available.当您
GET
该路由时,它将加载一个通用表单并将其呈现到页面,而没有设置或可用的任何myField3
选项。
You can control the form to load based on certain criteria by using the __init__
override:您可以使用
__init__
覆盖控制基于特定条件加载的表单:
class ToolForm(FlaskForm):
myField3 = SelectField(u'Select Account', choices=[], coerce=int)
def __init__(self, accounts=None):
super().__init__() # calls the base initialisation and then...
if accounts:
self.myField3.choices = [(c.id, c.name) for c in accounts]
Then you will construct the form from some other information based on the route request:然后您将根据路由请求从其他一些信息构建表单:
@app.route("/test", methods=['GET', 'POST'])
def test():
# define accounts
form = ToolForm(accounts=accounts)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.