Flask/WTForms - post request doesnt send input

不羁岁月 提交于 2020-01-05 09:30:15

问题


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

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