gpt4 book ai didi

python - 带有 BooleanField 的 Flask WTForms FieldList

转载 作者:行者123 更新时间:2023-11-28 22:24:04 25 4
gpt4 key购买 nike

我想生成带有复选框的文件列表。我试过使用 FieldList 但它没有像我预期的那样工作。我得到的不是带有指定文件名的复选框,而是带有以包含 FieldList 对象的变量命名的标签的复选框。有什么办法可以解决吗?

应用.py:

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import BooleanField, FieldList, SubmitField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'development'
Bootstrap(app)

filenames = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']


class FileListForm(FlaskForm):
filename = FieldList(BooleanField(), 'Files')
submit = SubmitField('Submit')


@app.route('/')
def listfiles():
form = FileListForm()
for filename in filenames:
form.filename.append_entry(filename)
return render_template('index.html',
form=form)


if __name__ == '__main__':
app.run(debug=True, port=5001)

模板/index.html

{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}

包:

click==6.7
dominate==2.3.1
Flask==0.12.2
Flask-Bootstrap==3.3.7.1
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
visitor==0.1.3
Werkzeug==0.12.2
WTForms==2.1

最佳答案

根据文档,WTForms 的 FieldList不应与 BooleanField 一起使用:

Note: Due to a limitation in how HTML sends values, FieldList cannot enclose BooleanField or SubmitField instances.

(即使 HTML 输出看起来有效。)也就是说,您没有看到您期望看到的内容,因为 append_entry 的第一个参数接受表单输入的值,而不是它的标签.

相反,我建议动态创建表单类:

filenames = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']

class FileListFormBase(FlaskForm):
submit = SubmitField('Submit')

def file_list_form_builder(filenames):
class FileListForm(FileListFormBase):
pass

for (i, filename) in enumerate(filenames):
setattr(FileListForm, 'filename_%d' % i, BooleanField(label=filename))

return FileListForm()

@app.route('/')
def listfiles():
form = file_list_form_builder(filenames)
return render_template('index.html', form=form)

注意:默认的 HTML 表示将在顶部具有“提交”按钮,因为库按照定义的顺序呈现字段。 WTForms 本身不支持排序,所以这可能是一个更好的解决方案,尽管它不太优雅:

filenames = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']

def file_list_form_builder(filenames):
class FileListForm(FlaskForm):
pass

for (i, filename) in enumerate(filenames):
setattr(FileListForm, 'filename_%d' % i, BooleanField(label=filename))

setattr(FileListForm, 'submit', SubmitField('Submit'))
return FileListForm()

@app.route('/')
def listfiles():
form = file_list_form_builder(filenames)
return render_template('index.html', form=form)

关于python - 带有 BooleanField 的 Flask WTForms FieldList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com