Flask WTForms

Define Forms and Fields

  1. Define a form
  2. Add string field
  3. Add radio field, set default value
  4. Add submit field
from flask_wtf import FlaskForm
from wtforms import StringField, RadioField, SubmitField, validators, ValidationError

class WeatherForm(FlaskForm):
    location = StringField()
    unit = RadioField(choices=[('metric', '\u00b0C'), ('imperial', '\u00b0F')],
                      default='metric')
    search = SubmitField(label='Search')
    history = SubmitField(label='History')
    help = SubmitField(label='Help')
    wrong_data = SubmitField(label='Wrong Data?')

Build-in validators

  1. Add InputRequired validator
  2. Add Length validator
from wtforms import StringField, validators


location = StringField(validators=[validators.Length(max=50)])
description = StringField(label='Description', validators=[validators.InputRequired(message='Description is required.'),validators.Length(max=50, message='Description cannot be longer than 50 characters.'))

Custom validator

  1. Custom validator for string field: description
  2. If the input description is not valid, raise error
  3. Valid descriptions are stored in a list
  4. The items in the list are queried from database with distinct, then use join to convert the tuple to string.
from wtforms import StringField, validators, ValidationError
from sqlalchemy import distinct
from weather import db
from weather.models import Description

class ValidateDescription(object):
    def __init__(self, message=None):
        if not message:
            message = 'Description is not valid, please check help.'
        self.message = message

    def __call__(self, form, field):
        valid_weather = []
        for d in db.session.query(distinct(Description.description)).all():
            d = ''.join(d)
            valid_weather.append(d)

        if field.data.strip() not in valid_weather:
            raise ValidationError(self.message)

class UpdateForm(FlaskForm):
    description_validator = ValidateDescription()
    description = StringField(label='Description', validators=[validators.InputRequired(message='Description is required.'), validators.Length(max=50, message='Description cannot be longer than 50 characters.'), description_validator])

results matching ""

    No results matching ""