我正在使用Flask构建一个非常简单的注册表单,我想要自定义
在表单中,当我将
那么为什么这些错误没有被添加到“errors”中,而自定义消息也没有生效?这两者有关联吗?
DataRequired
和Email
验证器的错误消息,但似乎我的自定义消息被忽略了,而是打印默认消息。以下是我的代码片段:
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
{% 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
{% 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
字段留空时,我收到的验证弹出消息是“请填写此字段”,这应该是默认的吧。我还尝试在这些字段留空时打印form.errors
,但奇怪的是errors
字典为空。
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”中,而自定义消息也没有生效?这两者有关联吗?
signup.html
文件吗? - Chien Nguyen