问题
WTForms-JSON docs here.
This has been a bug from hell I cannot wrap my head around.
I have a simple API handler that works perfectly fine from Postman JSON POSTs.
However when I plug the data into a web form the JSON is all empty. For example:
162.249.161.234 - - [23/May/2017 10:52:55] "POST /submitworkorder HTTP/1.1" 200 -
{'customer': None}
My Flask is as follows:
@app.route('/')
def index():
form = SubmitWorkorderForm.from_json(request.json)
print form.data
return render_template('submitworkorder.html', form = form)
@app.route('/submitworkorder', methods=['POST'])
def submitworkorder():
form = SubmitWorkorderForm.from_json(request.json)
print form.data
if form.validate_on_submit():
customer = form.customer.data
return jsonify({'customer' : customer })
And my HTML:
<div class="container">
<form class="form-inline">
{{ form.customer }}
{{ form.hidden_tag() }}
<input type="submit" value="go"/>
</form>
<br>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
Lastly my JS:
$(document).ready(function() {
console.log("form Data:", $('form').serialize())
$.ajax({
type: "POST",
dataType: "json",
url : "/submitworkorder",
data : $('form').serialize(),
success: function (data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.customer + 'successfully created.').show();
$('#errorAlert').hide();
}
}
});
});
I have been working on this for the better part of 8 hours with no progress at all. Any help is appreciated.
回答1:
This was caused by some old documentation floating around. WTForms has built in support for handling serialized JSON now, you don't need the from_json
or the request.json
anymore.
Simply import and instantiate your form as you would.
Fixed code as follows:
@app.route('/')
def index():
form = SubmitWorkorderForm.from_json()
print form.data
return render_template('submitworkorder.html', form = form)
来源:https://stackoverflow.com/questions/44138994/wtforms-json-not-receiving-form-data