Flask-WTFform: Flash does not display errors

。_饼干妹妹 提交于 2020-06-09 10:25:49

问题


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

Here is one of my form classes:

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

And view:

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


回答1:


There are no errors yet because you haven't processed the form yet

Try putting the flash_errors on the else of the validate_on_submit method

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


来源:https://stackoverflow.com/questions/13585663/flask-wtfform-flash-does-not-display-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!