简体   繁体   中英

WTForms can't seem to validate a SelectField box

I've produced a select field for staff to choose their name. My goal for when the user does not select their name, but instead leaves the drop down box on the selection "---", In this scenario I want the ValidationError to then print it's message. At the moment nothing is printed when I test this.

Here is my forms.py files:

from flask_wtf import Form
from wtforms import StringField, BooleanField, SelectField
from wtforms.validators import DataRequired, Required, ValidationError 

class StaffNames(Form):
        staff = SelectField(
        'staff',
        choices=[("", "---"), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('3', 'Lyn Fox')],
        )
        def validate_staff(form, field):
                if field.data is "---":
                        raise ValidationError("Sorry, you havn't chosen a staff name")

Here is my view.py file:

from flask import render_template, flash, redirect
from app import app
from .forms import StaffNames

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = StaffNames()
    if form.validate_on_submit():
        return redirect('/results')
    return render_template('index.html',
                           title='RA Index Search',
                           form=form)

here is my index.html which relates to this form:

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}
<center>
    <h1>Search</h1>
    <form action="" method="post" name="login">

        <p>{{ form.staff }} Select your name</p>
        <p><input type="submit" value="Search"></p>
    </form>

{% endblock %}

Can anyone see what I am doing wrong or suggest an alternative that won't melt my brain! lol Thanks

As far as i see there are two errors in your code:

  1. You need to include a csrc_token in your template form otherwise your form.validate_on_submit() method will always return False. Also make sure you set the app.config['SECRET_KEY'] to some value.

  2. In Your validation method you check for the data property of the SelectBox being '---'. This will never happen as data refers to the first value of the tuple you pass in your list of choices .

Change your validate_staff method the following way and you should be fine:

def validate_staff(form, field):
    if field.data == "":
        raise ValidationError("Sorry, you havn't chosen a staff name")

class StaffNames(Form):

    staff = SelectField(
        'staff',
        choices=[
            ("", "---"), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('3', 'Lyn Fox')],
        validators=[validate_staff],
    )

NOTE: You need to pass the validate_staff function to the validators list of the StaffNames form otherwise the validation will never get triggered. I changed the above code accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM