使用 Flask-WTF 时从字典填充 WTForms 表单
Populate WTForms form from dictionary when using Flask-WTF
我有一个需要从字典中填充的 Flask-WTF 表单,我将其作为 **kwargs
传入。该表单在使用 POST
方法访问的 Flask 路由中使用。表单未通过验证,字段值为 None
。如何将数据字典传递到我的表单然后对其进行验证?
@app.route('/submit', methods=['POST'])
def submit():
data = {'name': 'eee'}
form = MyForm(**data)
print(form.validate()) # False, name is required
print(form.name.data) # None
您必须为构造函数使用 data 参数。您还可以查看 documentation
form = MyForm(data=data)
Flask-WTF automatically passes request.form
when the route is posted to, if no data is passed explicitly. You need to pass your data, as a MultiDict
, to prevent the automatic behavior. Passing obj
, data
, or **kwargs
, only sets the defaults, which are only used 如果没有向表单传递真实数据。
form = MyForm(MultiDict(data))
我有一个需要从字典中填充的 Flask-WTF 表单,我将其作为 **kwargs
传入。该表单在使用 POST
方法访问的 Flask 路由中使用。表单未通过验证,字段值为 None
。如何将数据字典传递到我的表单然后对其进行验证?
@app.route('/submit', methods=['POST'])
def submit():
data = {'name': 'eee'}
form = MyForm(**data)
print(form.validate()) # False, name is required
print(form.name.data) # None
您必须为构造函数使用 data 参数。您还可以查看 documentation
form = MyForm(data=data)
Flask-WTF automatically passes request.form
when the route is posted to, if no data is passed explicitly. You need to pass your data, as a MultiDict
, to prevent the automatic behavior. Passing obj
, data
, or **kwargs
, only sets the defaults, which are only used 如果没有向表单传递真实数据。
form = MyForm(MultiDict(data))