Reputation: 5136
I'm using Flask (vsn 0.8) and Flask-WTF (vsn 0.5.2) (e.g., to parse forms) to make a pretty simple website. However, I'm unable to get Flask-WTF to properly parse my GET results.
My relevant code looks like this:
@app.route("/result", methods=("GET", "POST"))
def submit():
form = MyForm()
print request.args
print request.args.get('aws_id', None, type=str)
print form.is_submitted()
if form.validate_on_submit():
flash('Success')
aws_id = form.aws_id.data
return render_template("index.html", form=form)
If I submit my form with a single field called 'aws_id' with GET I get the following output on the console.
127.0.0.1 - - [19/Oct/2011 22:28:59] "GET /result?aws_id=test_string HTTP/1.1" 200 -
ImmutableMultiDict([('aws_id', u'test_string')])
test_string
False
It looks to me like the submit is working correctly, but Flask-WTF isn't doing its thing. Essentially, the old way of dealing with form output works, the request.args.get method, but the new form.is_submitted and form.validate_on_submit aren't doing their magic goodness.
Any ideas? (WTF!)
Upvotes: 0
Views: 3095
Reputation: 33833
Flask-WTF's Form
class is_submitted
method looks like:
def is_submitted(self):
"""
Checks if form has been submitted. The default case is if the HTTP
method is **PUT** or **POST**.
"""
return request and request.method in ("PUT", "POST")
And in its __init__
has this code, which normally ensures formdata is loaded automatically from Flask request:
if formdata is _Auto:
if self.is_submitted():
formdata = request.form
So it's clear... if you submit the form via GET you don't get any of the nice auto behaviour. This is understandable because if it's a GET request it's not clear whether the form was submitted or you were just loading the page. This is aside from any CSRF issues.
validate_on_submit
doesn't work either, as it also relies upon is_submitted
Flask itself also doesn't parse the GET fields into request.form
for you.
You end up having to do something like:
form = MyForm(request.args, csrf_enabled=False)
if 'aws_id' in request.args and form.validate():
flash('Success')
aws_id = form.aws_id.data
(all assume your MyForm
class inherits from from flask.ext.wtf import Form
)
Upvotes: 3
Reputation: 5136
I moved my app to the root of my site, deleted the one that was there (=redundant), and added request.form
to the MyForm class. That seems to fix it. It was also necessary to set csrf_enabled
to false.
@app.route("/", methods=("GET", "POST"))
def submit():
form = MyForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
print form.data
return render_template("index.html", form=form)
Upvotes: 2