当前位置: 首页 > 工具软件 > WTForms > 使用案例 >

wtforms表单验证

彭星津
2023-12-01

wtforms表单的两个主要功能是验证用户提交数据的合法性以及渲染模板。安装wtforms的命令为:pip install wtforms。

如下是表单来做数据验证:

import wtforms
from wtforms.validators import length, email


class LoginForm(wtforms.Form):
    username = wtforms.StringField(validators=[email(), length(min=6, max=20)])
    password = wtforms.StringField(validators=[length(min=6, max=20)])

写完表单后就是html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="/login" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td>
                <input name="username" type="text">
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input name="password" type="password">
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <button type="submit">登录</button>
            </td>
        </tr>

    </table>
</form>
</body>
</html>

视图函数:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        print(request.form)
        form = LoginForm(request.form)
        if form.validate():
            print(form.validate())
            return '登录成功!!'
        else:
            return '用户名或密码错误!!'
 类似资料: