5

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)

I send the following JSON-request

{
    "name": "Alex",
    "address": {
        "street": "Plz Work Street",
        "number": 1337
    }
}

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!

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.