简体   繁体   中英

Flask object has no attribute 'validate_on_submit'

I got a problem with the form.validate_on_submit() method from wtforms , it throws the following error every time when I submit the form:

'LoginForm' object has no attribute 'validate_on_submit'

forms.py:

from wtforms import Form, validators, StringField, PasswordField

class LoginForm(Form):
    email = StringField('Email Address', [validators.DataRequired(message='Field required')])
    password = PasswordField('Password', [validators.DataRequired(message='Field required')])

routes.py

from flask import Flask, escape, request, render_template, redirect, url_for
from securepi import app, tools
from securepi.forms import LoginForm
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
try:
    form = LoginForm(request.form)

    if request.method == "POST" and form.validate_on_submit():
        email = str(form.email.data)
        password = tools.encrypt(str(form.password.data))
        print("email:  {}, password: {}".format(email, password))


        # if valid account create session and redirect to index


        return redirect(url_for('index'))
    else:
        print("FAIL")
        error = "Invalid username or password"

except Exception as e:
    return(str(e))

return render_template('login.html', form = form)

and the form

<form action="" method="post">
  <div class="form-group has-feedback">
    <input type="email" name="email" class="form-control" placeholder="Email" value="{{ request.form.email }}">
    <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
  </div>
  <div class="form-group has-feedback">
    <input type="password" name="password" class="form-control" placeholder="Password" value="{{ request.form.password }}">
    <span class="glyphicon glyphicon-lock form-control-feedback"></span>
  </div>
  <div class="row">
    <!-- /.col -->
    <div class="col-xs-12">
      <button type="submit" class="btn btn-primary btn-block">Log in</button>
    </div>
    <!-- /.col -->
  </div>
</form>

Can you try changing your forms.py to the following?

from flask_wtf import FlaskForm
from wtforms import validators, StringField, PasswordField

class LoginForm(FlaskForm):
    email = StringField('Email Address', [validators.DataRequired(message='Field required')])
    password = PasswordField('Password', [validators.DataRequired(message='Field required')])

Forms class docs say:

validate()

Validates the form by calling validate on each field, passing any extra Form.validate_<fieldname> validators to the field validator.

Seems like you are trying to validate on_submit field which is missing from form. Simply using validate() should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM