Nested forms (FormFields) doesn’t get populated with data when I use WTForms-JSON. I can’t spot my mistake, see example below.
JavaScript
x
37
37
1
from flask import Flask, request, jsonify
2
from flask_wtf import Form
3
from wtforms import TextField, FormField, IntegerField
4
from wtforms.validators import InputRequired
5
import wtforms_json
6
7
app = Flask(__name__)
8
app.config["WTF_CSRF_ENABLED"] = False
9
wtforms_json.init()
10
11
12
class Address(Form):
13
street = TextField('street', validators=[InputRequired()])
14
number = IntegerField('number', validators=[InputRequired()])
15
16
17
class User(Form):
18
name = TextField('name', validators=[InputRequired()])
19
address = FormField(Address, label='address')
20
21
22
@app.route('/', methods=['POST'])
23
def why_no_work():
24
form = User()
25
26
form.from_json(request.json)
27
print form.data
28
29
if form.validate():
30
return jsonify(success='YEAH')
31
else:
32
return jsonify(errors=form.errors)
33
34
35
if __name__ == '__main__':
36
app.run(debug=True)
37
I send the following JSON-request
JavaScript
1
8
1
{
2
"name": "Alex",
3
"address": {
4
"street": "Plz Work Street",
5
"number": 1337
6
}
7
}
8
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).
Print output:
{'name': u'Alex', 'address': {'street': u'', 'number': None}}
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!
Advertisement
Answer
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.
JavaScript
1
9
1
@app.route('/', methods=['POST'])
2
def why_no_work():
3
form = User.from_json(request.json) # <-- This line right here
4
5
if form.validate():
6
return jsonify(success='YEAH')
7
else:
8
return jsonify(errors=form.errors)
9