user3717963
user3717963

Reputation: 189

Flask/WTForms - post request doesnt send input

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

Upvotes: 1

Views: 3061

Answers (1)

nikihub
nikihub

Reputation: 321

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.

Upvotes: 3

Related Questions