在 Flask 路由中从 wtforms FormField 获取数据
getting data from wtforms FormField in a Flask route
我在路由中使用表单从表单获取数据时遇到问题
forms.py
class Calculator(Form):
amount = IntegerField('Amount')
weight = IntegerField('Weight')
class Program(Form):
cycles = IntegerField('Cycles')
volume = FormField(Calculator)
app.py
@app.route('/', methods=('GET', 'POST'))
def index():
form = forms.Program()
if form.validate_on_submit():
values = models.Progression(
cycles=form.cycles.data,
amount=form.amount.data,
weight=form.weight.data
)
return render_template('index.html', form=form, values=values)
cycles
的数据通过得很好,但我不确定如何在我的路由中访问封装表单的语法。文档说 FormField
将 return 所附表格的数据字典,但我似乎无法弄清楚如何获取它并将其放入变量中。
问题是表单数据没有作为 Calculator
class 的属性传递。数据作为字典从 volume
属性发送。
测试一下:print form.volume.data
(我建议注释掉您的 values
对象并只使用打印语句)
输出应该是:{'amount': foo, 'weight': bar}
谢谢你教我一些东西!我从来不知道 FormField
。
我能够使用
获取我需要的数据
amount=form.volume.amount.data,
weight=form.volume.weight.data
真正的问题是当我使用 FormField
时表单没有验证。我应该早点检查的菜鸟错误。
我必须通过从 flask_wtf
导入它并使用 CsrfProtect(app)
来启用 CSRF 保护
我在路由中使用表单从表单获取数据时遇到问题
forms.py
class Calculator(Form):
amount = IntegerField('Amount')
weight = IntegerField('Weight')
class Program(Form):
cycles = IntegerField('Cycles')
volume = FormField(Calculator)
app.py
@app.route('/', methods=('GET', 'POST'))
def index():
form = forms.Program()
if form.validate_on_submit():
values = models.Progression(
cycles=form.cycles.data,
amount=form.amount.data,
weight=form.weight.data
)
return render_template('index.html', form=form, values=values)
cycles
的数据通过得很好,但我不确定如何在我的路由中访问封装表单的语法。文档说 FormField
将 return 所附表格的数据字典,但我似乎无法弄清楚如何获取它并将其放入变量中。
问题是表单数据没有作为 Calculator
class 的属性传递。数据作为字典从 volume
属性发送。
测试一下:print form.volume.data
(我建议注释掉您的 values
对象并只使用打印语句)
输出应该是:{'amount': foo, 'weight': bar}
谢谢你教我一些东西!我从来不知道 FormField
。
我能够使用
获取我需要的数据 amount=form.volume.amount.data,
weight=form.volume.weight.data
真正的问题是当我使用 FormField
时表单没有验证。我应该早点检查的菜鸟错误。
我必须通过从 flask_wtf
导入它并使用 CsrfProtect(app)