Flask 对象没有属性 'validate_on_submit'

Flask object has no attribute 'validate_on_submit'

我在 wtforms 的 form.validate_on_submit() 方法中遇到问题,每次提交表单时都会抛出以下错误:

'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)

和表格

<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>

您可以尝试将 forms.py 更改为以下内容吗?

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 文档说:

validate()

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

您似乎正在尝试验证表单中缺少的 on_submit 字段。只需使用 validate() 即可解决问题。