wtforms-form generation and validation

introduce

wtforms is a form component that supports multiple web frameworks, mainly used for form validation and generation,

Install

pip install wtforms

use

Customize a class, inherit the wtforms.Form class, and define fields

from wtforms import Form
from wtforms.fields import simple,core,html5 # fields come from here
from wtforms import validators # validation rules come from here
from wtforms import widgets # tools are here

class LoginForm(Form):
    user = simple.StringField(
            label='username', # prompt information
            validators=[validators.DataRequired(message='Username cannot be empty.')], #List of validation rules
            widget=widgets.TextInput(), # Render the input tag in the way he defines first
            render_kw={'class': 'form-control'} # Set properties for the input tag
    )

render

Instance custom class object, passed into the template, if data is passed in the instance object, the data will be rendered into the input box

{{ form.name }} # The input box of the field
{{ form.name.label }} # This field prompts information
{{ form.name.errors[0] }} # The error information of the field, it is recommended to use this method, the following error information of the field will throw an exception
{{ form.errors }} # full error message

# You can also use a for loop, and its order will not be confused, because a counter is maintained inside the Form
{% for item in form %}
        <p>{{item.label}}: {{item}} {{item.errors[0] }}</p>
{% endfor %}

verify

Instance custom class object is to pass data

form = LoginForm(formdata=request.form)
if form.validate():
    # Verification passed, print data
    print(form.data)
else:
    print(form.error) # print error message

field

Three packages simple, core, html5 are provided in wtforms.fields

simple is simple and commonly used including:

['BooleanField', 'TextAreaField', 'PasswordField', 'FileField',
    'HiddenField', 'SubmitField', 'TextField']

core is less commonly used

(
    'BooleanField', 'DecimalField', 'DateField', 'DateTimeField', 'FieldList',
    'FloatField', 'FormField', 'IntegerField', 'RadioField', 'SelectField',
    'SelectMultipleField', 'StringField',
)

The tags in html5 have their own regularity (browser verification)

(
    'DateField', 'DateTimeField', 'DateTimeLocalField', 'DecimalField',
    'DecimalRangeField', 'EmailField', 'IntegerField', 'IntegerRangeField',
    'SearchField', 'TelField', 'URLField',
)

  It should be noted here that core.RadioField (single selection), core.SelectField (drop-down menu), core.SelectMultipleField (multiple selection drop-down menu) have a coerce attribute, which specifies the type of data conversion (because the data obtained from the front end are all String), if it is not converted to the corresponding data type, the validation will fail.

In addition, if we want to dynamically obtain the value of choices, we can rewrite the __init__ method in the class we wrote. Get it every time you instantiate it, and then execute the __init__ in the parent class to get it in real time. updated options

class RegisterForm(Form):
    city = core.SelectField(
        label='city',
        choices=SQLHelper.fetch_all('select id,name from city',{},None),
        coerce=int
    )
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.city.choices = PymysqlConn.fetch_all('select id,name from city',{},None)

validation rules

A number of validation rules are provided in wtforms.validators

(
    'DataRequired', 'data_required', 'Email', 'email', 'EqualTo', 'equal_to',
    'IPAddress', 'ip_address', 'InputRequired', 'input_required', 'Length',
    'length', 'NumberRange', 'number_range', 'Optional', 'optional',
    'Required', 'required', 'Regexp', 'regexp', 'URL', 'url', 'AnyOf',
    'any_of', 'NoneOf', 'none_of', 'MacAddress', 'mac_address', 'UUID'
)

Here are some commonly used

DataRequired: non-null validation, message=error message

Email: Email format verification, message=error message

Length: length verification, min=shortest, max=longest, message=error message

Regexp: regular match, regex regular expression, message=error message

EqualTo: Is it the same as the value of other fields, fieldname=other field name, message=error message

Custom Validation-Hook

# Set validation for a field
def validate_fieldname(self, field):
    print(field.data) # The value passed from the current field
    print(self.data) # All values ​​currently passed in: name, gender.....
    if validation failed:
        raise validators.ValidationError("Continue subsequent validation")
        # raise validators.StopValidation("Do not continue subsequent validation")

small parts

wtforms.widgets provides many form styles, each field has a default widget, and the rendered style can be modified by setting the widget

('CheckboxInput', 'FileInput', 'HiddenInput', 'ListWidget', 'PasswordInput',
    'RadioInput', 'Select', 'SubmitInput', 'TableWidget', 'TextArea',
    'TextInput', 'Option')

Checkbox settings

favor = core.SelectMultipleField(
        label='Preferences',
        choices=(
            (1, 'basketball'),
            (2, 'football'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2]
    )

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065276&siteId=291194637