Danish Xavier
Danish Xavier

Reputation: 1167

Why the wtforms not generating error when the Validators condtion is not met?

So I am working on a form which has two inputs and a check condition. If the check condition is not satisfied raise error. Else take the value in the db. Given below is my forms.py script.

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators

# Define QuoteForm below
class QuoteForm(FlaskForm):
  # qauthor = StringField("Quote Author",[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =100,message = "Field must be between 3 and 100 characters long.")])
  qauthor = StringField("Quote Author",validators=[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =100,message = "Field must be between 3 and 200 characters long.")])
  qstring = StringField("Quote",validators=[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =200,message = "Field must be between 3 and 200 characters long.")])
  submit = SubmitField(" Add Quote")

As you can see the min length should be greater than 3 for both fileds. I am also capturing the error in the HTML page addquote.html

<body>
<h2>QuoteForm</h2>
<form action="", method="post">
  <p>
    {{form.qauthor.label}} : {{form.qauthor}}<br>
    {%for error in form.qauthor.errors%}
    <span style="color: red;">[{{ error }}]</span><br>

    {% endfor %}

  </p>
    <p>
    {{form.qstring.label}} : {{form.qstring}}<br>
    {%for error in form.qstring.errors%}
    <span style="color: red;">[{{ error }}]</span><br>
    {% endfor %}
  </p>

    <p>{{form.submit}}</p>
</form>
</body>

I am calling the form in my flask function. Given below.

@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
    form = QuoteForm()
    if form.is_submitted():
        breakpoint()
        result = request.form
        qqauthor = result['qauthor']
        qqstring = result['qstring']
        add_tab = Quotes(quoteauthor=qqauthor,quotestring=qqstring)
        db.session.add(add_tab)
        db.session.commit()
        return render_template("addquote_confirmation.html")

    return render_template("addquote.html",form=form)

I am not getting an error for both these cases where I have mentioned the condition in my forms.py minimum length to be 3. Why the error is not coming or validation is not happening? Dependency: flask_wtf=='0.14.3' flask=='1.0.2'

Upvotes: 3

Views: 682

Answers (1)

pjcunningham
pjcunningham

Reputation: 8046

You need to call the form's validate() method. This is more conveniently done calling validate_on_submit(), which is a shortcut for checking the active request is a submission (POST, PUT, PATCH, or DELETE) and the form's data is valid (see docs).

@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
    form = QuoteForm()
    if form.validate_on_submit():
        breakpoint()
        add_tab = Quotes(quoteauthor=form.qqauthor.data, quotestring=form.qqstring.data)
        db.session.add(add_tab)
        db.session.commit()
        return render_template("addquote_confirmation.html")

    return render_template("addquote.html",form=form)

Simple full example code below, no database just print out form's data.

app.py

from flask import Flask, render_template, url_for
from flask_wtf import FlaskForm
from markupsafe import Markup
from wtforms import StringField, SubmitField, validators


class QuoteForm(FlaskForm):
    author = StringField(
        "Quote Author",
        validators=[
            validators.DataRequired(message="This field is required"),
            validators.Length(min=3, max=100, message="Field must be between 3 and 200 characters long.")
        ]
    )
    quote = StringField(
        "Quote",
        validators=[
            validators.DataRequired(message="This field is required"),
            validators.Length(min=3, max=200, message="Field must be between 3 and 200 characters long.")
        ]
    )
    submit = SubmitField(" Add Quote")


app = Flask(__name__)
app.config['SECRET_KEY'] = 'MY SECRET KEY'


@app.route('/', methods=['GET'])
def index():
    _quote_url = url_for('add_quote')
    return Markup(f'<a href="{_quote_url}">Add Quote</a')


@app.route('/add-quote/', methods=['GET', 'POST'])
def add_quote():
    form = QuoteForm()
    if form.validate_on_submit():
        print(f'Author: {form.author.data}')
        print(f'Quote: {form.quote.data}')
        return "Quote form is validated"

    return render_template("add-quote.html", form=form)


if __name__ == '__main__':
    app.run()

add-quote.html

<body>
<h2>QuoteForm</h2>
<form action="" method="post">
    {{ form.csrf_token }}
    <p>
        {% for error in form.errors %}
            <span style="color: red;">[{{ error }}]</span><br>
        {% endfor %}
    </p>
    <p>
        {{ form.author.label }} : {{ form.author }}<br>
        {% for error in form.author.errors %}
            <span style="color: red;">[{{ error }}]</span><br>

        {% endfor %}

    </p>
    <p>
        {{ form.quote.label }} : {{ form.quote }}<br>
        {% for error in form.quote.errors %}
            <span style="color: red;">[{{ error }}]</span><br>
        {% endfor %}
    </p>

    <p>{{ form.submit }}</p>
</form>
</body>

Upvotes: 2

Related Questions