Raising an error in WTForm using jinja2

时光毁灭记忆、已成空白 提交于 2019-12-24 10:12:19

问题


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 ?

here is the main 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)

and here is the template:

  <!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>

回答1:


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.

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.




回答2:


Add your own message instead of default message in your form defination.

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



回答3:


As Matt Healy before mentiones, it is the browser that validates URLField. So if you want a custom error message use StringField (TextField is outdated). If required, a custom message can be used as shown below message='text to display'. Example:

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

Of course the *.html should include code to output an error to the page:

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



回答4:


It seems like novalidate attribute works for your case.



来源:https://stackoverflow.com/questions/45535373/raising-an-error-in-wtform-using-jinja2

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