2016-01-19 34 views
0

我需要用许多复选框构建一个简单的窗体。问题是,我需要的复选框来自csv文件这将是这样的:简单的动态窗体Flask/Flask-WTF

data_so.csv

Name 
A. Blabla 
U. Blublu 
I. Blibli 
O. Bloblo 

的形式,现在,有一些硬编码的复选框,如下所示:

enter image description here

而不是“1先生”,我需要有“A BLABLA”,而不是“2女士”,我会想“U Blublu”等,而不是3个复选框,我需要4,我的csv文件中的条目数。

这里是我的瓶文件:

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工作提供变量undifined数...

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文件的东西?如果不是,在加载客户端时动态生成表单的常用方法是什么?

回答

1
{% for node in node_list_from_app %} 
    <p class="field"><label><input type="checkbox" name="node" value="{{ node }}"> {{ node }}</label></p> 
{% endfor %} 

+0

谢谢!我也需要改变form_so.py中的Python代码,不是吗? – Rodolphe

+1

当然,但我是新手,并且只使用普通Flask,没有WTForms,所以我不确定,应该如何更改应用程序中的代码。 – CtrlD