Consider this Flask-WTF form field definition:
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])What HTML does the name field render by default?
Think about the default HTML input type for a StringField in Flask-WTF.
A StringField renders as a standard text input field in HTML, which uses type="text". Other types like password or email are different field classes.
You want to create a form field that accepts only integers greater than or equal to 10. Which code snippet correctly defines this field?
Look for the validator that checks numeric ranges.
NumberRange validator is used to enforce minimum and maximum numeric values. DataRequired, Length, and InputRequired do not accept a min parameter for numeric range.
Given this Flask-WTF form:
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])If the user submits the form with the username field left empty, what will be the value of form.username.data after form.validate_on_submit() is called?
Think about how WTForms handles empty text input fields.
WTForms sets the data attribute to an empty string if the input is empty. Validation fails but the data is still an empty string, not None or an exception.
Examine this form field definition:
from wtforms import SelectField
class MyForm(FlaskForm):
choice = SelectField('Choose', choices='yes,no,maybe')When rendering or validating, a TypeError occurs. Why?
Check the expected type for the choices parameter.
choices must be a list (or iterable) of tuples like [('yes', 'Yes'), ('no', 'No')]. Passing a string causes iteration over characters, leading to a TypeError.
You want users to upload several files at once in your Flask form. Which field type is best suited for this?
Look for a field type designed specifically for multiple files.
MultipleFileField is designed to handle multiple file uploads in Flask-WTF. FileField handles single files only. Other options are not suitable for file uploads.