Flask-WTFform:Flash不显示错误

时间:2012-11-27 13:48:11

标签: python flask wtforms

我正在尝试刷新WTForm验证错误。我找到了this snippet并略微修改了它:

 def flash_errors(form):
    """Flashes form errors"""
    for field, errors in form.errors.items():
        for error in errors:
            flash(u"Error in the %s field - %s" % (
                getattr(form, field).label.text,
                error
            ), 'error')

这是我的一个表单类:

class ContactForm(Form):
    """Contact form"""
    # pylint: disable=W0232
    # pylint: disable=R0903
    name = TextField(label="Name", validators=[Length(max=35), Required()])
    email = EmailField(label="Email address",
                       validators=[Length(min=6, max=120), Email()])
    message = TextAreaField(label="Message",
                            validators=[Length(max=1000), Required()])
    recaptcha = RecaptchaField()

并查看:

@app.route("/contact/", methods=("GET", "POST"))
def contact():
    """Contact view"""
    form = ContactForm()
    flash_errors(form)
    if form.validate_on_submit():
        sender = "%s <%s>" % (form.name.data, form.email.data)
        subject = "Message from %s" % form.name.data
        message = form.message.data
        body = render_template('emails/contact.html', sender=sender,
                               message=message)
        email_admin(subject, body)
        flash("Your message has been sent. Thank you!", "success")

    return render_template("contact.html",
                           form=form)

但是,验证失败时不会闪烁错误。我知道我的表单和模板工作正常,因为我的成功消息在数据有效时闪烁。有什么问题?

1 个答案:

答案 0 :(得分:10)

还没有错误,因为您尚未处理表单

尝试将flash_errors放在else方法的validate_on_submit

@app.route("/contact/", methods=("GET", "POST"))
def contact():
    """Contact view"""
    form = ContactForm()
    if form.validate_on_submit():
        sender = "%s <%s>" % (form.name.data, form.email.data)
        subject = "Message from %s" % form.name.data
        message = form.message.data
        body = render_template('emails/contact.html', sender=sender,
                               message=message)
        email_admin(subject, body)
        flash("Your message has been sent. Thank you!", "success")
    else:
        flash_errors(form)

    return render_template("contact.html",
                       form=form)