Flask-WTFform:Flash不显示错误 [英] Flask-WTFform: Flash does not display errors

查看:100
本文介绍了Flask-WTFform:Flash不显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试刷新WTForm验证错误.我找到了此代码段,并对其做了一些修改:

I'm trying to flash WTForm validation errors. I found this snippet and slightly modified it:

 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)

但是,验证失败时不会闪现任何错误.我知道我的表单和模板可以正常工作,因为当数据有效时,成功消息会闪烁.怎么了?

However, no errors are flashed upon validation failures. I know my forms and templates work fine, because my success message flashes when the data is valid. What is wrong?

推荐答案

由于您尚未处理表单,因此没有错误

尝试将flash_errors放在validate_on_submit方法的else

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

这篇关于Flask-WTFform:Flash不显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆