6.Flask-WTForms

6.Flask-WTForms

 Flask-WTF is a third-party library that simplifies the operation of WTForms. The two main functions of the WTForms form are to verify the validity of the data submitted by the user and to render the template. There are other functions: CSRF protection,

File upload, etc. Installation method: pip install flask-wtf

1.1. WTForms simple verification

from flask import Flask,request,render_template
from wtforms import Form,StringField
from wtforms.validators import Length,EqualTo

app = Flask(__name__)

class RegistForm(Form):
    username = StringField(validators=[Length(min=3,max=10,message='Username must be between 3 and 10 digits')])
    password = StringField(validators=[Length(min=6,max=10,message='password must be between 6 and 10 digits')])
    password_repeat = StringField(validators=[Length(min=6,max=10),
                                              EqualTo("password",message='Passwords are inconsistent')])

@app.route('/')
def hello_world():
    return'Hello World!'

@app.route('/regist/',methods=['GET','POST'])
def regist():
    if request.method =='GET':
        return render_template('regist.html')
    else:
        form = RegistForm(request.form)
        if form.validate():
            return'success'
        else:
            print(form.errors)
            return'fail'

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

1.2. WTForms commonly used validators and custom validators

 Common validators

  • Email: Verify whether the uploaded data is in mailbox format
  • EqualTo: Are the two fields equal (password and repeated password)
  • InputRequired: the need to verify the original data
  • Length: Length limit, there are two values ​​of mix and max
  • NumberRange: The range of numbers, there are two values ​​of mix and max, if it is between the two values, it is satisfied
  • Regexp: custom regular expression
  • URL: must url format
  • UUID: uuid format
from wtforms import Form,StringField,IntegerField
from wtforms.validators import Length,EqualTo,Email,InputRequired,NumberRange
from wtforms.validators import Regexp,URL,ValidationError


class LoginForm(Form):
    email = StringField(validators=[Email(message='Email format is incorrect')])
    username = StringField(validators=[InputRequired(message='This field must be filled in')])
    age = IntegerField(validators=[NumberRange(min=18,max=100)])
    phone = StringField(validators=[Regexp(r'1[38745]\d{9}')])
    homepage = StringField(validators=[URL()])
    captcha = StringField(validators=[Length(4,4)])

    # Custom validator
    def validate_captcha(self,field):
        if field.data != '1234': #field.data: data submitted by the user
            raise ValidationError('Verification code error') #If the verification fails, throw a verification failure exception

1.3. Use wtforms to render the template

 forms.py

class SettingsForm(Form):
    username = StringField(label="Username:",validators=[InputRequired(message='This field must be filled in')])
    age = IntegerField('age:',validators=[NumberRange(min=18, max=100)])
    remeber = BooleanField('Remember me')
    tags = SelectField('tag',choices=[(1,'python'),(2,'django')])

flask_wtforms_demo.py

@app.route('/settings/',methods=['GET','POST'])
def settings():
    if request.method =='GET':
        form = SettingsForm()
        return render_template('settings.html',form=form)
    else:
        pass

settings.html

<form action="" method="post">
{# You can add styles in the brackets#}
    <p>{{ form.username.label }} {{ form.username(class="") }}</p>
    <p>{{ form.age.label }} {{ form.age() }}</p>
    <p>{{ form.remeber.label }} {{ form.remeber() }}</p>
    <p>{{ form.tags.label }} {{ form.tags() }}</p>
    <p><input type="submit" value="Submit"></p>
</form>
Reference: https://cloud.tencent.com/developer/article/1172851 6.Flask-WTForms-Cloud + Community-Tencent Cloud