wtforms 基本使用

作者: ropon 分类: Flask 发布时间: 2019-04-10 16:17
from flask import Flask, request, render_template
from wtforms.fields import simple, core
from wtforms import validators
from wtforms import Form


app = Flask(__name__)


class LoginForm(Form):
    username = simple.StringField(
        label="用户名", # 标签标记
        validators=[
            validators.DataRequired(message="用户名不能为空"),
            validators.Length(min=3, max=10, message="用户名必须%(min)d-%(max)d个字符")
        ], # 校验条件 可迭代对象
        id="user_id", # 标签ID
        default=None, # 默认值
        widget=None, # 默认组件
        render_kw={"class": "my_login"} # 模板渲染配置信息
    )
    password = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="密码不能为空"),
            validators.Length(min=6, max=12, message="密码必须%(min)d-%(max)d个字符")
        ],
        id="pwd_id",
        render_kw={"class": "my_login"}
    )
    repassword = simple.PasswordField(
        label="确认密码",
        validators=[validators.EqualTo(fieldname="password", message="两次输入密码不一致")]
    )
    gender = core.RadioField(
        label="性别",
        coerce=int,
        choices=(
            (1, "男"),
            (2, "女")
        ),
        default=1
    )


@app.route('/', methods=["GET", "POST"])
def hello_world():
    lf = LoginForm()
    if request.method == "POST":
        lf = LoginForm(request.form)
        if lf.validate():
            return lf.data.get("username")
    return render_template("login.html", wtf = lf)



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

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!