我尝试根据用户上传的csv中的列名动态填充下拉列表。用户上传文件(变量名是文件名)并重定向到下一页/ analysis /后,如何将文件名实际传递给SimpleForm(form)类以实际生成下拉列表? 代码是问题
form = SimpleForm(filename)
我知道我无法直接将文件名传递给SimpleForm类(对象),但我该怎么做?
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class SimpleForm(Form):
list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
# create a list of value/description tuples
files = [(x, x) for x in list_of_files]
test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
second_list = list(test.columns)
second_files = [(x, x) for x in second_list]
acheckbox = MultiCheckboxField('Label', choices=files)
bcheckbox = MultiCheckboxField('Label', choices=second_files)
categories = SelectField('Label',choices = files)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
if columns_len(filename):
title = filename.split('.')[0].title() #creates the title
return redirect(url_for('analysis', filename=filename))
else:
flash(u'Your CSV has less than three columns. Please re-upload', 'error')
else:
flash(u'Invalid file type. Please re-upload', 'error')
return render_template('index.html')
@app.route('/analysis/<filename>', methods=['GET','POST'])
def analysis(filename):
form = SimpleForm(filename)
return render_template('analysis.html', filename=filename, form=form)
答案 0 :(得分:1)
您必须定义__init__
方法以接受您的参数并在那里设置choices
。
class SimpleForm(Form):
acheckbox = MultiCheckboxField('Label')
bcheckbox = MultiCheckboxField('Label')
categories = SelectField('Label')
def __init__(self, filename, *args, **kwargs):
super(SimpleForm, self).__init__(*args, **kwargs)
list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
# create a list of value/description tuples
files = [(x, x) for x in list_of_files]
test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
second_list = list(test.columns)
second_files = [(x, x) for x in second_list]
self.acheckbox.choices = files
self.bcheckbox.choices = second_files
self.categories.choices = files