使用 jinja2 在 WTForm 中引发错误

Raising an error in WTForm using jinja2

我试图在 Jinja2 中引发错误,在 WTForm 中,如果 url 输入未经验证,则应该引发错误,但是当我提交无效 url 时,我得到弹出窗口说 "Please enter a url".

如何传递默认弹出窗口并添加自定义错误消息?

这里是主要的py:

from datetime import datetime
from flask import Flask, render_template, url_for, request, redirect,flash
from logging import DEBUG
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from flask.ext.wtf.html5 import URLField
from wtforms.validators import DataRequired , url


app = Flask(__name__)
app.logger.setLevel(DEBUG)
app.config['SECRET_KEY']='{@\x8d\x90\xbf\x89n\x06%`I\xfa(d\xc2\x0e\xfa\xb7>\x81?\x86\x7f\x1e'


@app.route('/')
@app.route('/index')

def index():
    return render_template('base.html')

@app.route('/add', methods=['GET','POST'])
def add():
    return render_template('add.html')


# HERE IS THE LOGIN FORM
class Login(FlaskForm):
    username = StringField('username')
    password = PasswordField('password')
    url = URLField('url', validators=[DataRequired(),url()])

@app.route('/form', methods=['GET','POST'])
def form():
    form = Login()
    if form.validate_on_submit():
        url = form.url.data
        return redirect(url_for('index'))
    return render_template('form.html',form = form )


if __name__ =='__main__':
    app.run(debug=True)

这是模板:

  <!DOCTYPE html>
<html>
<head>
    <title>form</title>
</head>
<body>
 <h1>Hello !</h1>
 <form method="POST" action="{{url_for('form')}}">
 {{ form.hidden_tag() }}
 {{ form.csrf_token }}
 {{ form.username.label }}
 {{ form.username }}
 {{ form.password.label }}
 {{ form.password }}
 {{ form.url.label }}
 {{ form.url }}
  {% if form.url.errors %} <p> {{error}}</p> {% endif %}
 <button type="submit">Submit</button>
 </form>
</body>
</html>

因为您使用的是数据类型 URLField,所以它呈现为 HTML5 "url" 表单字段类型。

您的浏览器识别这一点并对提交的数据执行自己的验证:

您无法覆盖它 - 它内置于浏览器中。

如果您需要显示自定义错误消息,您可以改用 TextField,并提供您自己的 URL 验证逻辑。

在表单定义中添加您自己的消息而不是默认消息。

url = URLField('url', validators=[DataRequired(),url(message="Please enter a valid url (e.g.-http://example.com/)")]) 

看来 novalidate attribute 适合你的情况。

正如 Matt Healy 之前提到的,验证 URLField 的是浏览器。 因此,如果您想要自定义错误消息,请使用 StringFieldTextField 已过时)。如果需要,可以使用自定义消息,如下所示 message='text to display'。 示例:

class XYZForm(FlaskForm):
    url = StringField('url', validators=[DataRequired(),url(message='Please enter valid URL')])
    description = StringField('description')

当然,*.html 应该包含向页面输出错误的代码:

                <ul>
                    {% for error in form.url.errors %}
                        <li>{{ error }}</li>
                    {% endfor %}
                </ul>