Flask Study Note 6

Views: 171
Wrote on May 15, 2020, 9:41 p.m.

WTForms is a flexible forms validation and rendering library for Python web development. It can work with whatever web framework and template engine you choose. It supports data validation, CSRF protection, internationalization (I18N), and more. There are various community libraries that provide closer integration with popular frameworks.

pip install WTForms email_validator

Example

# app.py

from wtforms.fields import simple, core
from wtforms import Form
from wtforms import validators
from wtforms import widgets


class LoginForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[validators.DataRequired(message="不能为空"),
                    validators.Length(min=3, max=5, message="长度必须大于3小于5")],
        # filters=tuple(),
        # description='',
        # id=None,
        # default=None,
        # widget=widgets.TextInput(),
        render_kw={"class":"my_username"} # 这里不能写 id
    )

    password = simple.PasswordField(
        label="密码",
        validators=[validators.DataRequired(message="不能为空"),
                    validators.Length(min=6, max=6, message="长度必须为6位"),
                    validators.Regexp(regex="\d+", message="密码必须为数字")],
        render_kw={"class":"my_password"}
    )


class RegForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[validators.DataRequired(message="不能为空"),
                    validators.Length(min=3, max=5, message="长度必须大于3小于5")],
        render_kw={"class":"my_username"}
    )


    nickname = simple.StringField(
        label="昵称",
        validators=[validators.DataRequired(message="不能为空")],
        render_kw={"class":"my_nickname"}
    )

    password = simple.PasswordField(
        label="密码",
        validators=[validators.DataRequired(message="不能为空"),
                    validators.Length(min=6, max=6, message="长度必须为6位"),
                    validators.Regexp(regex="\d+", message="密码必须为数字")],
        render_kw={"class":"my_password"}
    )

    re_password = simple.PasswordField(
        label="重复密码",
        validators=[validators.EqualTo(fieldname="password", message="两次密码不一致")],
    )

    email = simple.StringField(
        label="邮箱",
        validators=[validators.Email(message="格式不正确"),],
        render_kw={"class":"my_email"}
    )

    gender = core.RadioField(
        label="性别",
        # validators=None,
        coerce=int,
        choices=(
            (1,"女"),
            (2,"男"),
        ),
        default=1
    )

    hobby = core.SelectMultipleField(
        label="爱好",
        # validators=None,
        coerce=int,
        choices=(
            (1,"小姐姐"),
            (2,"小萝莉"),
            (3,"大叔"),
            (4,"小哥哥"),
            (5,"小正太"),
            (6,"小奶狗"),
            (7,"老阿姨"),
        ),
        default=(1,2,7)
    )

    submit = simple.SubmitField()


class LoginClass(views.MethodView):

    def get(self):
        lf = LoginForm()
        return render_template("login.html", lf=lf)

    def post(self):
        lf = LoginForm(request.form)
        if lf.validate():
            return "Success"
        else:
            return render_template("login.html", lf=lf)


class RegClass(views.MethodView):

    def get(self):
        rf = RegForm()
        return render_template("register.html", rf=rf)

    def post(self):
        rf = RegForm(request.form)
        if rf.validate():
            return "Success"
        else:
            return render_template("register.html", rf=rf)


app.add_url_rule("/login", endpoint=None, view_func=LoginClass.as_view("login"))
app.add_url_rule("/register", endpoint=None, view_func=RegClass.as_view("register"))
// login.html

<form action="" method="post" novalidate>
  {{ lf.username.label }}{{ lf.username }}{{ lf.username.errors.0 }}
  <br>
  {{ lf.password.label }}{{ lf.password }}{{ lf.password.errors.0 }}
  <br>
  <input type="submit" value="Login">
</form>
// register.html

<form action="" method="post" novalidate>
  {% for field in rf %}
    <p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p>
  {% endfor %}
</form>