WTForms doesn't raise any validation error

24 Views Asked by At

I made a basic login page with flask and wtforms. But the validators' errors aren't displaying on the page even though I think I correctly wrote the code. I first made a wtforms class LoginForm that takes username and password fields, using the wtforms.validator InputRequired. So if a field is empty when the form is submitted, the field should add the default message "This field is required" to it's errors attribute (accessed in index.html).

This is the app.py:

from flask import Flask, request, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired

app = Flask(__name__)
app.config["SECRET_KEY"] = "sampleSecretKey"

class LoginForm(FlaskForm):
    username = StringField("username", validators=[InputRequired()])
    password = PasswordField("password", validators=[InputRequired()])

@app.route("/", methods=["GET", "POST"])
def home():
    form = LoginForm()
    if form.validate_on_submit():
        return "Form submitted"
    
    return render_template("index.html", form=form)

if __name__ == "__main__":
    app.run(debug=True)

This is index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="", method="POST">
        {{ form.csrf_token }}
        {{ form.username.label }}
        {{ form.username }}
        <ul>
        {% for error in form.username.errors %}
        <li style="color:red">{{ error }}</li>
        {% endfor %}
        </ul>

        {{ form.password.label }}
        {{ form.password }}

        <input type="submit" value="Login">
    </form>
</body>
</html>

Intended behaviour: When I click the submit(called "Login" here) button with the username field empty, it should display "This field is required" in red colour.
But when I run it and click on the login button, it doesn't display that, but instead the default prompt generated by HTML (seperate from the form.username.errors prompt in the above code). I know that this prompt is different since it comes due to the required flag set by the InputRequired validator on the input {{ form.username }}, as an attribute if you look at the raw HTML. Like this:

promptImage

How do I get the intended output?

0

There are 0 best solutions below