如何正确地将列 headers 添加到 WTForms 动态选择字段列表中
How to properly add column headers into WTForms dynamic selectfield list
我有一个 Pandas 数据框,并试图将 return 列 headers 放入 Flask 应用程序的 WTForm 动态列表中。
但是,当我尝试提交 HTML 表单时,出现验证错误。这是我的表格 class 错误。
data = pd.read_excel("sampledata.xlsx")
col_headers = list(data.columns)
col_list = list(col_headers)
dic_list = {i : col_list[i] for i in range(0, len(col_list))}
class StatementForm(FlaskForm):
date = SelectField('Date', choices = [(key, dic_list[key]) for key in dic_list])
我已经通过在选择列表中手动输入一个元组来测试 HTML 表单并且它有效。显然问题出在 'date' 参数和选项中。
非常感谢您在审查代码方面的帮助。
尝试使用以下内容来创建您的选择:
choices = [(str(x), y) for (x, y) in list(enumerate(data.columns))]
区别在于上面代码中的值是一个字符串。根据 WFT-Forms 文档:
Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.
在您的版本中,您试图传递整数作为值,这就是它被破坏的原因。
我有一个 Pandas 数据框,并试图将 return 列 headers 放入 Flask 应用程序的 WTForm 动态列表中。 但是,当我尝试提交 HTML 表单时,出现验证错误。这是我的表格 class 错误。
data = pd.read_excel("sampledata.xlsx")
col_headers = list(data.columns)
col_list = list(col_headers)
dic_list = {i : col_list[i] for i in range(0, len(col_list))}
class StatementForm(FlaskForm):
date = SelectField('Date', choices = [(key, dic_list[key]) for key in dic_list])
我已经通过在选择列表中手动输入一个元组来测试 HTML 表单并且它有效。显然问题出在 'date' 参数和选项中。
非常感谢您在审查代码方面的帮助。
尝试使用以下内容来创建您的选择:
choices = [(str(x), y) for (x, y) in list(enumerate(data.columns))]
区别在于上面代码中的值是一个字符串。根据 WFT-Forms 文档:
Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.
在您的版本中,您试图传递整数作为值,这就是它被破坏的原因。