使用jinja2在WTForm中引发错误 [英] Raising an error in WTForm using jinja2
问题描述
我正在尝试在WTForm中在Jinja2中引发错误,如果未验证url输入,则应该引发该错误,但是当我提交无效的url时,会弹出一个对话框,提示请输入url".
I'm trying to raise an error in Jinja2, in a WTForm, the error should be raised if url input is not validated, but when i submit an invalide url, i get a popup saying "Please enter a url".
如何传递默认弹出窗口并添加自定义错误消息?
how do i pass the default popup and add a custom error message ?
这是主要的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"表单字段类型.
Because you're using the data type URLField
, this is rendered as a HTML5 "url" form field type.
您的浏览器会识别出这一点,并对提交的数据执行自己的验证:
Your browser recognises this and performs its own validation on the data submitted:
您无法覆盖它-它内置在浏览器中.
There is no way for you to override this - it's built in to the browser.
如果需要显示自定义错误消息,则可以改用TextField
,并提供自己的URL验证逻辑.
If you need to show a custom error message, you might be able to use a TextField
instead, and provide your own URL validation logic.
这篇关于使用jinja2在WTForm中引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!