eightHundreds
12/26/2016 - 2:46 AM

flask_wtf展示出检测失败的信息

flask_wtf展示出检测失败的信息

 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"""
    name = TextField(label="Name", validators=[Length(max=35), Required(message='custom msg')],)
    
@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)#errors created after validate_on_sumit called

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