Flask WTForms always give false on validate_on_submit()

独自空忆成欢 提交于 2019-12-02 01:15:33

I solved my problem with the following function:

def __init__(self, *args, **kwargs):
    kwargs['csrf_enabled'] = False
    super(ProfileInfoForm, self).__init__(*args, **kwargs)

I added this function in ProfileInfoForm()

The issue was FormField includes csrf_token field as well as Actual form, i.e., RegistrationForm was also including csrf_token, so there were two csrf_token which were to be verified and only one was getting rendered actually in form. So, I disabled csrf_token in ProfileInfoForm so when FormField rendered it, it had csrf_token = False.

And RegistrationForm does have csrf_token enabled still now so the form is still safe.

My Guess is this does also required to be done in FormField as well.

FYI: This solution might be wrong due to my interpretation of the FormField code. SO please correct me if I am wrong in above solution.

I had the same issue and I was able to fix it.

The problem was related to the fact that the LoginForm had the id and username with a validators while the html form was not requiring the information

            <h1>Login</h1>

            <form action="" method="POST"  name="login">
        {{ login_form.csrf_token }}
        {{ login_form.hidden_tag() }}

        <p>
            {{ login_form.email.label }}<br>
            {{ login_form.email(size=64) }}<br>
            {% for error in login_form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ login_form.password.label }}<br>
            {{ login_form.password(size=32) }}<br>
            {% for error in login_form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ login_form.remember_me }} Remember Me</p>
{#            <input type="submit" value="Sign In">#}
        <p>{{ login_form.submit() }}</p>
    </form>



class LoginForm(FlaskForm):
    ***# user_id = StringField('user_id',validators=[DataRequired()])
    # user_name = StringField('user_name',validators=[DataRequired(), Length(min=3, max=20)])***
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('remember_me', default=False)
    submit = SubmitField('LogIn')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!