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
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 %}
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
@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')
And this is what I get
------{}
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 -
So why these errors are not being added the errors
and why the custom messages are not taking effect.Are these related some how ?