I am using Flask, Pandas, WTForms.
I want to populate a selectfield with data from a csv file.
I have
routes.py
forms.py
tabular.html
I create form in forms.py then via routes.py display it into 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)
tabular.html
<form method="POST" action="">
...
{{ form.country.label }} {{ form.country }}
{{ form.state.label }} {{ form.state}}
...
</form>
csv file format
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,,,,,,
Now I want to pull only the values "USA","India" etc and populate in the selectfield "form.country". I have tried to do a for loop on routes.py. But how do I pass it on to the HTML file ? I also tried to do a for loop via Jinja on the HTML file.
How do I dynamically populate the "choices" attribute of the WTF selectfield from the html file ?