Flask-wtforms are similar to form components in django

Posted by fuji on Fri, 04 Oct 2019 22:04:00 +0200

I. installation

pip3 install wtforms

II. Simple Use

1. Create flask objects

from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets

app = Flask(__name__, template_folder='templates')

app.debug = True

II. Generating form Components

class LoginForm(Form):
    # Fields (which contain regular expressions)
    name = simple.StringField(
        label='User name',  #Form form label
        validators=[   #Some Conditions for Filtration
            validators.DataRequired(message='User name cannot be empty.'),
            validators.Length(min=6, max=18, message='User name length must be greater than%(min)d And less than%(max)d')
        ],
        widget=widgets.TextInput(), # Plug-ins displayed on the page
        render_kw={'class': 'form-control'}  #The class name displayed on the form page

Three. Routing

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        form = LoginForm() #Generate form objects
        return render_template('login.html', form=form)  #form object rendering
    else:
        form = LoginForm(formdata=request.form) 
        if form.validate():   #form checking
            print('The data submitted by the user is validated by the format, and the value submitted is:', form.data)
        else:
            print(form.errors)
        return render_template('login.html', form=form)

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

4. Page Rendering

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Sign in</h1>
<form method="post">
    <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p>

    <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p>
    <input type="submit" value="Submission">
</form>
</body>
</html>

III. Relevant attributes

1.field field field

WTForms supports HTML fields:

Field type Explain
StringField Text field, equivalent to the input tag of type text
TextAreaField Multi-line text field
PasswordField Password text field
HiddenField Hidden text fields
DateField Text field, value in datetime.date format
DateTimeField Text field, value in datetime.datetime format
IntegerField Text field with integer value
DecimalField Text field, value decimal.Decimal
FloatField Text field with floating point value
BooleanField Check boxes with values of True and False
RadioField A set of radio boxes
SelectField Drop-down list
SelectMultipleField Drop-down list, multiple values can be selected
FileField File upload field
SubmitField Form submission button
FormFiled Embedding a form as a field into another form
FieldList Subgroup field of specified type

2.Validators Verifier

WTForms can support many form validation functions:

Validation function Explain
Email Verification is an e-mail address
EqualTo Compare the values of two fields; often used in situations where two keys are required for confirmation.
IPAddress Verify IPv4 Network Address
Length Verify the length of the input string
NumberRange Verify that the input value is within the numerical range
Optional Skip other validation functions without input values
DataRequired Ensure that there is data in the field
Regexp Validate input values using regular expressions
URL Verify url
AnyOf Ensure that input values are in the list of optional values
NoneOf Ensure that input values are not in the optional list

3. Field parameters

Parameter name introduce
label Field alias, which can be displayed in the page by field. label
validators Validation Rule List
filters Perchlorinator list for filtering submitted data
description Description information, usually used to generate help information
id Represents the position of the field when the form class is defined. Usually you don't need to define it. By default, it will be sorted in the order of definition.
default Default value
widget html plug-in, through which you can override the default plug-in, more through user customization
render_kw Customize html properties
choices Options for Check Types

4. Local hook

#In the form class
def validate_Field name(self, field):
        #self.data obtains a dictionary-like format for global fields
        #self.data ['field'], you can get any field in the global
        #Value of the current field of field.data
        #There is no need to return a value, and errors should be thrown if there are unsatisfactory situations.
        #If you have two passwords, there are two situations.
        # raise validators.ValidationError("Inconsistent passwords") # Continue subsequent validation
        #  raise validators.StopValidation("Inconsistent passwords")  # No further follow-up validation

5. Modify the value without changing the model

#In the form class
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.Field name.choices = ((1, 'Basketball'), (2, 'Football'), (3, 'Badminton'))

4. Written templates

from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets

app = Flask(__name__, template_folder='templates')
app.debug = True



class RegisterForm(Form):
    name = simple.StringField(
        label='User name',
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'},
        default='cxw'
    )

    pwd = simple.PasswordField(
        label='Password',
        validators=[
            validators.DataRequired(message='Password cannot be empty.')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    pwd_confirm = simple.PasswordField(
        label='Repeat password',
        validators=[
            validators.DataRequired(message='Duplicate password cannot be empty.'),
            validators.EqualTo('pwd', message="Two inconsistent password input")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    email = html5.EmailField(
        label='mailbox',
        validators=[
            validators.DataRequired(message='Mailbox cannot be empty.'),
            validators.Email(message='Error in mailbox format')
        ],
        widget=widgets.TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    gender = core.RadioField(
        label='Gender',
        choices=(
            (1, 'male'),
            (2, 'female'),
        ),
        #The first value of the choices tuple above is the int type.
        #If the top is (`1', `male') and (`2', `female'), then the coerce below does not need to be written.
        coerce=int # "1" "2"
     )
    #Here is the radio box.
    city = core.SelectField(
        label='City',
        choices=(
            ('bj', 'Xie'),
            ('sh', 'Xie'),
        )
    )
    #Here is the multi-check box.
    hobby = core.SelectMultipleField(
        label='hobby',
        choices=(
            (1, 'Basketball'),
            (2, 'Football'),
        ),
        coerce=int
    )
    #Here is the checkbox with multiple choices
    favor = core.SelectMultipleField(
        label='Like',
        choices=(
            (1, 'Basketball'),
            (2, 'Football'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2]
    )
    #Here we can change the value.
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.favor.choices = ((1, 'Basketball'), (2, 'Football'), (3, 'Badminton'))

    def validate_pwd_confirm(self, field):
        """
        //Customize the pwd_confirm field rule, for example: Is it consistent with the PWD field?
        :param field:
        :return:
        """
        # At the beginning of initialization, all the values in self.data already exist

            if field.data != self.data['pwd']:
            # raise validators.ValidationError("Inconsistent passwords") # Continue subsequent validation
            raise validators.StopValidation("Inconsistent passwords")  # No further follow-up validation


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        #Here you can pass default values
        form = RegisterForm(data={'gender': 2,'hobby':[1,]}) # initial
        return render_template('register.html', form=form)
    else:
        form = RegisterForm(formdata=request.form)
        if form.validate():
            print('The data submitted by the user is validated by the format, and the value submitted is:', form.data)
        else:
            print(form.errors)
        return render_template('register.html', form=form)



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

Topics: Python html5 less network