WTForms-JSON not working with FormFields

穿精又带淫゛_ 提交于 2019-12-22 08:34:49

问题


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:


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)


来源:https://stackoverflow.com/questions/28508228/wtforms-json-not-working-with-formfields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!