Flask-WTF 表单没有属性 'validate_on_submit'

Flask-WTF form doesn't have attribute 'validate_on_submit'

我正在使用 Flask-WTF 在提交时验证表单。我正在使用 form.validate_on_submit(),但出现以下错误:

AttributeError: 'PickASong' object has no attribute 'validate_on_submit'

为什么会出现此错误,我该如何解决?

import flask
from flask import Flask
from flask import render_template
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask.ext.wtf import Form
from wtforms import *
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from wtforms import Form, TextField, BooleanField, PasswordField, TextAreaField, validators

class PickASong(Form):
    song = TextField(u'Song title', validators=[DataRequired()])

class PickAnumber(Form):
    songNumber = IntegerField(u'Please select song number', validators=[DataRequired()])

app = Flask(__name__)

@app.route("/",methods=["POST","GET"])
def hello():
    form = PickASong(csrf_enabled=False)

    if form.validate_on_submit():
        user = form.song.data
        print user
        d=str(user)
        print d
        # search(d)
        cmd = "python Search.py --q \"" + d +'"'
        os.system(cmd)
        return redirect('/2')

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

您导入了 from flask.ext.wtf import Form,随后又导入了 from wtforms import *,其中包括基础 WTForms Form。所以名称 Form 指的是绑定到它的最后一个对象 wtforms.Form。这就是你避免 import * 的原因。快速修复是将 from flask_wtf import Form 移到 from wtforms import * 下面。正确的解决方法是只导入你需要的,而不是所有的。如果您需要两种形式,请为一个导入设置别名,这样名称就不会冲突:from flask_wtf import Form as FlaskForm.

您在顶部的大导入块下方多余地写入了以下导入。

from flask.ext.wtf import Form
from wtforms import Form, TextField, BooleanField, PasswordField, TextAreaField, validators

只是不要从 wtforms 导入 Form 或颠倒两行,以立即修复。

from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, PasswordField, TextAreaField, validators