1

I'm using Flask-WTF for form validation, but the validation is awalys failing.

app.py

from flask import Flask
from flask import request
from flask import jsonify

app = Flask(__name__)

@app.route('/add', methods=['POST'])
def add_survey_entry():

    form = Survey_Form(csrf_enabled=False)

    if not form.validate_on_submit():
        return jsonify({'test': request.data})

Survey_Form.py

from flask_wtf import Form
from wtforms import TextAreaField
from wtforms import validators
from wtforms import StringField
from wtforms import IntegerField
from wtforms import RadioField

class Survey_Form(Form):

    name = StringField('name', validators=[
        validators.optional(),
        validators.Length(min=3, max=50)
    ])

    age = IntegerField('age', validators=[
        validators.required(),
        validators.number_range(min=18, max=99)
    ])

    message = TextAreaField('message', validators=[
        validators.optional(),
        validators.length(max=500)
    ])

When I submit a POST request to http://example.com/add it always fails and request.data is empty. I use the following request:

curl http://127.0.0.1:5000/add -d "name=Bob&age=19&message=I+am+a+test+message"

Any ideas where I'm going wrong?

James Jeffery
  • 12,093
  • 19
  • 74
  • 108

1 Answers1

0

You should be use request.form instead of request.data as explained in https://stackoverflow.com/a/16664376/1182891

edit I meant in the response, not the form constructor

if not form.validate_on_submit():
    return jsonify({'test': request.form})
Community
  • 1
  • 1
Josh J
  • 6,813
  • 3
  • 25
  • 47
  • That works. But, do I have to pass this into my form? In the docs it says if I use `validate_on_submit` I don't have to pass in any form data. The problem still persists though, the validation fails even though the correct data is being sent. – James Jeffery Oct 09 '15 at 15:14
  • Scrap that, it works now. All I did was I removed `requests.form` and replaced it with `requests.errors`. That is very odd because that has nothing to do with the conditional above it. Saying that though, I switched from `RESTClient` to `curl` and noticed it working so it could be that. Thanks for the answer. – James Jeffery Oct 09 '15 at 15:16
  • 1
    I meant in the response, not in the form constructor. See my edit above. – Josh J Oct 09 '15 at 15:21