WTF表单验证

WTF表单验证可分为3个步骤:

①导入wtf扩展提供的表单验证器。(from wtforms.validators import DataRequired,EqualTo)

②定义表单类

# 定义表单类
class RegisterForm(FlaskForm):
    username =StringField('账号:',validators=[DataRequired()])
    password =PasswordField('密码:',validators=[DataRequired()])
    password2 = PasswordField('确认密码:',validators=[DataRequired(),EqualTo('password','两次密码不一致')])
    submit=SubmitField('提交')

③验证逻辑(判断请求方式——>请求参数——>验证)

redist_form=RegisterForm()

    if request.method=='POST':
        username=request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if redist_form.validate_on_submit():
            print(username,password)
            return 'success'
        else:
            flash('参数有误')
    return render_template('registform.html',form=redist_form)

完整代码:

app.py

from flask import Flask,render_template,request,flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField,SubmitField
from wtforms.validators import EqualTo,DataRequired
app = Flask(__name__)
app.secret_key='yingjie'

# 定义表单类
class RegisterForm(FlaskForm):
    username =StringField('账号:',validators=[DataRequired()])
    password =PasswordField('密码:',validators=[DataRequired()])
    password2 = PasswordField('确认密码:',validators=[DataRequired(),EqualTo('password','两次密码不一致')])
    submit=SubmitField('提交')

@app.route('/regist',methods=['GET','POST'])
def regist_form():
    redist_form=RegisterForm()

    if request.method=='POST':
        username=request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if redist_form.validate_on_submit():
            print(username,password)
            return 'success'
        else:
            flash('参数有误')
    return render_template('registform.html',form=redist_form)

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

registform.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
        {{ form.csrf_token() }}
        {{ form.username.label }}{{ form.username }}<br>
        {{ form.password.label }}{{ form.password }}<br>
        {{ form.password2.label }}{{ form.password2 }}<br>
        {{ form.submit }}
    </form>
{% for message in get_flashed_messages() %}
        {{ message }}
{% endfor %}
</body>
</html>

运行截图:

 

 

 

 

posted @ 2021-10-06 08:39  CherriesOvO  阅读(135)  评论(0编辑  收藏  举报