2016-01-19 65 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