Python Flask 解决form.validate_on_submit()总是为false的问题

# 表单类:
class Form(FlaskForm):
    username = StringField("用户名:", validators=[DataRequired()])
    phone = IntegerField("手机号:", validators=[DataRequired()])
    email = StringField("邮箱:", validators=[DataRequired(),email("Email ERROR")])
    age = IntegerField("年龄:", validators=[DataRequired()])
    about = TextAreaField("关于我:", validators=[DataRequired()])
    submit = SubmitField("注册")
    password = PasswordField("密码:", validators=[DataRequired()])
    confirm = PasswordField("确定密码:", validators=[DataRequired()])

# 视图函数:
@app.route("/",methods=["GET","POST"])
def index():
    form=Form()
    print(form.validate_on_submit())
    if form.validate_on_submit():
        return redirect(url_for("suc"))
    else:
        return render_template("register2.html",form=form)

@app.route("/suc")
def suc():
    return "SUCCESS"

 HTML代码:

{{ form.username.label }}
{{ form.username(class="form-control",placeholder="请输入用户名") }}
{{ form.password.label }}
{{ form.password(class="form-control",placeholder="输入密码") }}
{{ form.confirm.label }}
{{ form.confirm(class="form-control",placeholder="确认密码") }}
{{ form.phone.label }}
{{ form.phone(class="form-control",placeholder="输入手机号") }}
{{ form.email.label }}
{{ form.email(class="form-control",placeholder="输入邮箱") }}
{% for msg in form.email.errors %} {{ msg }} {% endfor %}
{{ form.age.label }}
{{ form.age(class="form-control",placeholder="输入年龄") }}
{{ form.about.label }}
{{ form.about(class="form-control",placeholder="输入我的简介") }}
{{ form.submit(class="btn btn-default") }}

我只用email一项进行测试。

这样呢form.validate_on_submit()返回的都是false,将表单类中含有中文字符串改成unicode字符解决中文编码问题

# 表单类:
class Form(FlaskForm):
    username = StringField(u"用户名:", validators=[DataRequired()])
    phone = IntegerField(u"手机号:", validators=[DataRequired()])
    email = StringField(u"邮箱:", validators=[DataRequired(),email("Email ERROR")])
    age = IntegerField(u"年龄:", validators=[DataRequired()])
    about = TextAreaField(u"关于我:", validators=[DataRequired()])
    submit = SubmitField(u"注册")
    password = PasswordField(u"密码:", validators=[DataRequired()])
    confirm = PasswordField(u"确定密码:", validators=[DataRequired()])

然后再把HTML代码中form标签里面加入{{ form.hidden_tag() }},这样form.validate_on_submit()才能起作用(我也不知道为啥要加。。)

你可能感兴趣的:(Error,flask,forms)