我需要构建一个包含许多复选框的简单表单。问题是我需要复选框来自csv文件,如下所示:
data_so.csv
Name
A. Blabla
U. Blublu
I. Blibli
O. Bloblo
现在,表格带有一些硬编码复选框,如下所示:
而不是"先生。 1",我需要" A。 Blabla"而不是" Ms。 2",我想要" U. Blublu"等等而不是3个复选框,我需要4,我的csv文件中的条目数。以下是我的Flask文件:
route_so.py
from flask import Flask, render_template, request, flash
from forms_so import ContactForm
import csv
app = Flask(__name__)
app.secret_key = 'development key'
@app.route('/', methods=['GET', 'POST'])
def home():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('home_so.html', form=form)
else:
print(form.node_1.data,form.node_2.data,form.node_3.data)
return render_template('home_so.html', success=True)
elif request.method == 'GET':
return render_template('home_so.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
form_so.py
from flask.ext.wtf import Form
import csv
from wtforms import TextField, RadioField, TextAreaField, SubmitField, validators, BooleanField
class ContactForm(Form):
# my attempt to force the creation of dynamic global variables
with open('/data_so.csv', 'rb') as f:
reader = csv.reader(f)
r = list(reader)
nodes = {}
for i in range(1,len(r)):
globals()[''.join("node_"+str(i))] = BooleanField(r[i][0])
# end of my attempt to force the creation of dynamic global variables
node_1 = BooleanField("Mr. 1")
node_2 = BooleanField("Ms. 2")
node_3 = BooleanField("Dr. 3")
# this needs to be dynamically set instead
submit = SubmitField("Send")
所以我尝试并创建了动态变量(以肮脏,黑客的方式)。现在的问题是,我不知道如何使home_so.html使用一个无数个变量...
home_so.html
{% extends "layout_so.html" %}
{% block content %}
{% if success %}
<p>Thank you for filling up our survey. We'll get back to you shortly.</p>
{% else %}
<form action="{{ url_for('home') }}" method=post>
{{ form.hidden_tag() }}
<h2>List of check boxes dynamically built from local csv file</h2>
#this needs to be dynamically set
{{ form.node_1.label }}
{{ form.node_1 }}
{{ form.node_2.label }}
{{ form.node_2 }}
{{ form.node_3.label }}
{{ form.node_3 }}
{{ form.submit }}
</form>
{% endif %}
{% endblock %}
有没有办法用简单的csv文件完成这类事情?如果没有,那么在加载客户端时动态生成表单的常用方法是什么?
答案 0 :(得分:1)
{% for node in node_list_from_app %}
<p class="field"><label><input type="checkbox" name="node" value="{{ node }}"> {{ node }}</label></p>
{% endfor %}