问题
does somebody know why the body of my post request is None? I am using Flask with WTForms.
My forms.py
class SignupForm(Form):
username = StringField('Username')
password = PasswordField('Password')
email = StringField('Email')
submit = SubmitField('Create account')
My route.py
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'POST':
app.logger.info(form.data)
return redirect(url_for('signup'))
elif request.method == 'GET':
return render_template('signup.html', form=form)
My signup.html
<form action="{{ url_for('signup') }}" method="POST">
{{ form.username.label }}
{{ form.username }}
{{ form.password.label }}
{{ form.password }}
{{ form.email.label }}
{{ form.email }}
{{ form.submit }}
</form>
app.logger.info(form.data) in my routes.py returns me
{'password': None, 'submit': False, 'username': None, 'email': None}
even though i give it a username etc. and i pressed the submit button
回答1:
Every time singup
is called you create an empty form. You should populate it with the data from the request(if present).
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm(request.form)
if request.method == 'POST':
# maybe call form.validate()
app.logger.info(form.data)
return redirect(url_for('signup'))
elif request.method == 'GET':
return render_template('signup.html', form=form)
WTForm is like a model definition. It's not directly coupled with Flask request, but it knows how to populate its fields from the request.
来源:https://stackoverflow.com/questions/34597943/flask-wtforms-post-request-doesnt-send-input