WTForms-JSON无法与FormFields一起使用 [英] WTForms-JSON not working with FormFields
问题描述
当我使用WTForms-JSON时,嵌套表单(FormFields)不会填充数据.我找不到我的错误,请参见下面的示例.
Nested forms (FormFields) doesn't get populated with data when I use WTForms-JSON. I can't spot my mistake, see example below.
from flask import Flask, request, jsonify
from flask_wtf import Form
from wtforms import TextField, FormField, IntegerField
from wtforms.validators import InputRequired
import wtforms_json
app = Flask(__name__)
app.config["WTF_CSRF_ENABLED"] = False
wtforms_json.init()
class Address(Form):
street = TextField('street', validators=[InputRequired()])
number = IntegerField('number', validators=[InputRequired()])
class User(Form):
name = TextField('name', validators=[InputRequired()])
address = FormField(Address, label='address')
@app.route('/', methods=['POST'])
def why_no_work():
form = User()
form.from_json(request.json)
print form.data
if form.validate():
return jsonify(success='YEAH')
else:
return jsonify(errors=form.errors)
if __name__ == '__main__':
app.run(debug=True)
我发送以下JSON请求
I send the following JSON-request
{
"name": "Alex",
"address": {
"street": "Plz Work Street",
"number": 1337
}
}
,但form.from_json(request.json)
之后的打印显示地址对象从未填充数据(同样,从路由返回适当的"错误).
but the print after form.from_json(request.json)
reveals that the address object is never populated with data (also, the "appropriate" errors are returned from the route).
打印输出:
{'name': u'Alex', 'address': {'street': u'', 'number': None}}
我正在使用WTForms 2.0.2,WTForms-JSON 0.2.8
I'm using WTForms 2.0.2, WTForms-JSON 0.2.8
这是错误还是我做错了什么?感谢您的帮助!
Is this a bug or am I doing something wrong? Thankful for any help!
推荐答案
我使用了from_json()函数错误,因为它是一个返回实例化形式的类函数.请参见下面的路线更新代码.
I was using the from_json()-function wrong, as it is a class-function that returns an instantiated form. See updated code for route below.
@app.route('/', methods=['POST'])
def why_no_work():
form = User.from_json(request.json) # <-- This line right here
if form.validate():
return jsonify(success='YEAH')
else:
return jsonify(errors=form.errors)
这篇关于WTForms-JSON无法与FormFields一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!