【发布时间】:2021-07-09 20:19:19
【问题描述】:
我正在使用 Flask、Pandas、WTForms。
我想用 csv 文件中的数据填充选择字段。
我有
routes.py
forms.py
tabular.html
我在 forms.py 中创建表单,然后通过 routes.py 将其显示到 tabular.html。
Forms.py
class QueryTableForm(FlaskForm):
state_select = []
district_select = []
country = SelectField(u'Country', choices=state_select)
state = SelectField(u'State', choices=district_select)
submit = SubmitField(u'Search')
Routes.py
#csv imports
country_wise_data = list(pd.read_csv('country_data.csv').values)
state_wise_data = list(pd.read_csv('state_data.csv').values)
district_wise_data = list(pd.read_csv('district_data.csv').values)
@app.route("/tabular", methods=['GET', 'POST'])
@login_required
def tabular():
form = QueryTableForm()
if form.validate_on_submit():
post = Post(title=form.country.data, content=form.state.data)
flash('Your Selection is Registered!', 'success')
return render_template('tabular.html', state_wise_data = state_wise_data,
country_wise_data=country_wise_data, district_wise_data=district_wise_data,
title='Tabular Data', form=form, legend='Tabular',
max=17000, date=date)
表格.html
<form method="POST" action="">
...
{{ form.country.label }} {{ form.country }}
{{ form.state.label }} {{ form.state}}
...
</form>
csv 文件格式
State,Confirmed,Recovered,Deaths,Active,Last_Updated_Time,,,,,,
USA,3458996,2834473,58245,564746,12-04-2021 22.57,,,,,,
India,1180398,1123133,4815,52128,13-04-2021 19.02,,,,,,
现在我只想提取值“USA”、“India”等并填充到选择字段“form.country”中。我试图在 routes.py 上做一个 for 循环。但是如何将它传递给 HTML 文件?我还尝试通过 Jinja 对 HTML 文件进行 for 循环。
如何从 html 文件中动态填充 WTF 选择字段的“选择”属性?
【问题讨论】:
标签: python flask jinja2 flask-wtforms wtforms