Wtforms自定义验证消息被忽略 [英] Wtforms custom validation message ignored

查看:49
本文介绍了Wtforms自定义验证消息被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flask建立一个非常简单的注册表单,我想为 DataRequired Email 验证程序自定义错误消息,但是看来我的自定义消息正在忽略,并显示默认消息.以下是我的代码段

I am building a very simple Sign Up form with flask and I wanted to customize the error message for DataRequired and Email validators, however it seems my custom messages are being ignored and the default messages are being printed. Below is my code snippet

forms.py

forms.py

class SignUp(FlaskForm):
    username = StringField('Username', validators=[DataRequired(message='Must be filled'), length(min=4, max=10)])
    email = EmailField('Email', validators=[DataRequired(message='Email can\'t be blank'),
                                            Email(message='valid email address required')])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
                                     validators=[DataRequired(), EqualTo('password', 'Passwords must match')])
    submit = SubmitField('Register')

signup.html

signup.html

{% extends "base.html" %}
{% from "jinja_helpers.html" import render_field %}
{% from "jinja_helpers.html" import render_button %}
{% block body %}
    <div class="container mt-4">
        <form action="" method="POST">
            {{ form.hidden_tag() }}
            {{ render_field(form.username) }}
            {{ render_field(form.email) }}
            {{ render_field(form.password) }}
            {{ render_field(form.confirm_password) }}
            {{ render_button(form.submit) }}
        </form>
        <div class="form-row mt-3">
            <small class="text-muted">Already have an account ? <a href="{{ url_for('login') }}">Log In</a></small>
        </div>
    </div>

{% endblock %}

jinja_helpers.html

jinja_helpers.html

{% macro render_field(field) %}
    <div class="form-group">
        {{ field.label(class="form-control-label font-weight-bold text-muted") }}
        {% if field.errors %}
            {{ field(class="form-control is-invalid") }}
            <div class="invalid-feedback">
                {% for error in field.errors %}
                    <span>{{ error }}</span>
                {% endfor %}
            </div>
        {% else %}
            {{ field(class="form-control") }}
        {% endif %}


    </div>
{% endmacro %}


{%  macro render_button(button) %}
    {{ button(class="btn btn-dark") }}
{%  endmacro %}

在表格上,当我将 username email 字段保留为空白时,我收到的验证弹出消息是请填写此字段",我猜这是默认设置.当我将此字段保留为空白并且奇怪的是 errors 字典为空时,我也尝试打印 form.errors .

On the form when I leave the username or email fields blank, the validation pop up message I get is "Please fill out this field" which is default I guess. I also tried to print form.errors when I leave this fields blank and strangely the errors dictionary is empty.

views.py

views.py

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignUp()
    print(f'------{form.errors}')
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        user = User(username, password)
        db.session.add(user)
        db.session.commit()
        flash('Account created successfully !', 'success')
        return redirect(url_for("login"))
    return render_template("signup.html", form=form, title='App-Sign Up')

这就是我得到的

------{}
127.0.0.1 - - [25/Jan/2019 19:08:34] "GET /signup HTTP/1.1" 200 -
127.0.0.1 - - [25/Jan/2019 19:08:34] "GET /static/css/main.css HTTP/1.1" 404 -

那么为什么不将这些错误添加到 errors 中,以及为什么自定义消息没有生效.这些相关如何?

So why these errors are not being added the errors and why the custom messages are not taking effect.Are these related some how ?

推荐答案

DataRequired Email 验证器的自定义验证消息的原因是由于浏览器是应用程序客户端正在使用这些验证程序的默认消息.覆盖默认值的方法是将 novalidate 消息附加到 html form .

The reason custom validation message for DataRequired and Email validator was because of the application client which is browser is using the defualt message for these validators. The way to override that default is by appending the novalidate message to the html form.

这告诉浏览器停止自行进行表单验证,以便可以由后端(在这种情况下为flask)进行处理.

This tells the browser to stop doing the form validations by itself, so that it can be handled by the backend which in this case is flask.

这是我必须对我的 signup.html 进行的唯一更改,并且效果很好.

This was the only change I had to make to my signup.html and it worked just fine.

这篇关于Wtforms自定义验证消息被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆