Flask WTForms always give false on validate_on_submit()

后端 未结 2 616
孤街浪徒
孤街浪徒 2021-01-20 17:39

I have created a signup form using wtforms. I am using FormField in it so that I don\'t have to repeat some of the elements of the form again. But whenever I click on the Su

相关标签:
2条回答
  • 2021-01-20 18:12

    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')
    
    0 讨论(0)
  • 2021-01-20 18:24

    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.

    0 讨论(0)
提交回复
热议问题