Search code examples
pythonflaskwebformsflask-wtformswtforms

Flask WTForms POST form error - validation error


I've been working on a project recently with Flask and have been stuck on one very annoying problem. I ended up making a simpler version to try make me understand the problem. It seems like all the inputs I am typing in the input boxes seem to be ignored and therefore the form is not validating.

Python Code - main.py

app.config['SECRET_KEY'] = "*****"

class UserForm(Form):
    username = StringField("Please enter a username", validators=[DataRequired()])
    email = StringField("Please enter a email", validators=[DataRequired()])
    submit = SubmitField("Sign Up")

@app.route('/', methods=['POST', 'GET'])
def index():
    username = None
    form = UserForm()
    print("######### ABOUT TO CHECK ###########")
    #if form.validate_on_submit():
    if request.method == 'POST' and form.validate():
        return 'Form Successfully Submitted!'
        username = form.username.data
        form.username.data = ''
        email = form.email.data
        form.password.data = ''
    else:
        print('Needs more work....')
    return render_template("page.html",
                          form=form,
                          username=username)

HTML Code - page.html

{% block content %}
{% if username %}
    <h1>Hello {{ username }}!!</h1>
{% else %}
    <form method="POST">
        {{ form.username.label }}
        {{ form.username() }}
        </br>
        {{ form.email.label }}
        {{ form.email() }}
        </br>
        {{ form.submit() }}
    </form>
{% endif %}
{% endblock %}

I have attempted using FlaskForm with 'for.hidden_tag()' however there was a problem with the CSRF token being missing (that may of occurred due to this problem).

When I run the code, before and after entering the inputs this appears on the console...

######### ABOUT TO CHECK ###########
Needs more work....
172.31.128.1 - - [08/Dec/2022 12:54:09] "GET / HTTP/1.1" 200 -

The 'ABOUT TO CHECK' and 'Needs more work...' are comments from me to check for the error.

Any help would be much appreciated, thank you.


Solution

  • To me, this looks like you are missing {{ form.csrf_token }} from your form.

    Try this:

    {% block content %}
    {% if username %}
        <h1>Hello {{ username }}!!</h1>
    {% else %}
        <form method="POST">
            {{ form.csrf_token }}
            {{ form.username.label }}
            {{ form.username() }}
            </br>
            {{ form.email.label }}
            {{ form.email() }}
            </br>
            {{ form.submit() }}
        </form>
    {% endif %}
    {% endblock %}
    

    And remember to use that commented out form.validate_on_submit() in your POST route.