我正在 Flask 中构建一个应用程序,它从不同的 CSV 文件中获取数据。我有不同的标签(CSV 文件中的列名称),对于每个标签,我有相同的下拉菜单。例如-
- 运输方式
- 多项选择
- 单选
- 颞叶
- 时间戳
- 多项选择
- 单选
- 颞叶
首先,我尝试创建这个模板。这是我的代码-
<div class="container">
<form class="col s12" action="/config" method="POST" enctype="multipart/form-data">
<div class="row">
<h2>Assign Fieldnames</h2>
{% for x in title %}
<label> {{ x }} :</label>
<select name="choice">
<option value="">Select One</option>
<option value="time">Temporal</option>
<option value="single">Single Choice</option>
<option value="multiple">Multiple Choice</option>
</select>
{% endfor %}
<input type="hidden" name="filename" value= {{filename}}></input>
<button class="btn" type="submit" value="Update">Submit</button>
</div>
</form>
</div>
查看
def config():
filepath = request.form['filename']
choice_to_make = ['Select one', 'Temporal', 'Single-Choice''Multi-
Choice']
print(filepath)
with open(filepath,'r') as csvfile:
reader = csv.reader(csvfile)
title = next(reader)
print(title)
return render_template('pages/placeholder.configure1.html',
title=title,choice_to_make= choice_to_make,
filename=filepath)
其次,我无法弄清楚如何为每个标签保存这些选择(多选、单选和临时),以便我可以在将此 CSV 发送到 Mongodb 后根据这些选择查询数据。
最佳答案
第一步是将每个标签选择选项与唯一的特定名称相匹配,以便能够在以下 View 中将它们关联起来。
模板
您可以使用循环索引来执行此操作。
{% for name in title %}
<label> {{ name }} :</label>
<select name="choice-{{ loop.index }}">
<option disabled selected value> Select One</option>
<option value="time">Temporal</option>
<option value="single">Single Choice</option>
<option value="multiple">Multiple Choice</option>
</select><br>
{% endfor %}
查看
下一步,在 View 中,您可以将表单给出的选择存储在字典或元组列表中(请参阅第二个建议)。重要的是采用一种能够在标题和选项之间保持轻松匹配的结构。
如果你想接下来调用特定的标题,字典会更有趣:
@app.route("/config", methods=['POST'])
def config():
choices = {}
with open(request.form['filename'], 'r') as csvfile :
reader = csv.reader(csvfile)
titles = next(reader)
for index, title in enumerate(titles,1):
choice = 'choice-' + str(index)
choices[title] = request.form.get(choice)
#choices = {'Mode of Transport': 'time', 'Timestamp':'multiple' }
<小时/>
列表可能更好地处理连续的所有标题并保持顺序:
choices = []
with open(request.form['filename'], 'r') as csvfile :
reader = csv.reader(csvfile)
titles = next(reader)
for index, title in enumerate(titles,1):
choice = 'choice-' + str(index)
choices.append((title, request.form.get(choice))
#choices = [('Mode of Transport','time'), ('Timestamp','multiple')]
关于python - 如何为不同的标签创建相同的下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841928/