• Flask系列09--Flask中WTForms插件,及自定义验证器


    一.概述

      django中的forms组件非常的方便,在flask中有WTForms的组件实现的也是类似的功能, 安装这个插件

    二.简单使用

      文档地址https://wtforms.readthedocs.io/en/latest/

      简单写一个注册的form

    # 注册表单
    class RegForm(Form):
        username = simple.StringField(
            label='用户名',
            validators=[validators.DataRequired(message='用户名不能为空')]
    
        )
    
        password = simple.PasswordField(
            label='密码',
            validators=[
                validators.DataRequired(message='密码不能为空'),
                validators.Length(min=1, max=10, message='密码长度不正确'),
            ]
        )
    
        re_password = simple.PasswordField(
            label='确认密码',
            validators=[
                validators.EqualTo('password', message='密码不一致')
            ]
        )
    
        email = simple.StringField(
            label='邮箱',
            validators=[
                validators.Email(message='邮箱格式不正确')
            ]
        )
    
        hobby = core.SelectMultipleField(
            label='爱好',
            choices=[
                (1, '足球'),
                (2, '篮球'),
                (3, '网球'),
            ],
    
            default=[1, 3],  # 设置默认值,
            coerce=int
    
        )
    
        gender = core.SelectField(
            label='性别',
            choices=[
                (1, ''),
                (2, '')
            ],
            default=1,
            coerce=int
        )
    
        sub = simple.SubmitField(
            label='提交',
            render_kw={'style': "color: red"},
        )

    这里写了sub按钮,在前端文件中如果不想让标签显示出来比如

    前端页面可以这样写

    <form action="" method="post" novalidate>
        {% for field in form_obj %}
            {% if field.type == "SubmitField" %}
                <p>{{ field }}{{ field.errors.0 }}</p>
            {% else %}
                <p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p>
            {% endif %}
        {% endfor %}
    </form>

    结果预览:

    三 . 自定义验证器 validator

      有两种写法,一种是类的,另外一种是写成函数

    1.函数

    class SignupForm(Form):
        age = IntegerField(u'Age')
        def validate_age(form, field):
            if field.data < 13:
                raise ValidationError("We're sorry, you must be 13 or older to register")

    2. 类

    # 自定义验证器,类 的写法
    class pwd_validator():
        def __init__(self, message=None):
            self.message = message
        def __call__(self, form, field):
            pwd = field.data
            if pwd != '123':
                raise ValidationError(self.message)

    示例 登陆:

    # 自定义验证器,类 的写法
    class pwd_validator():
        def __init__(self, message=None):
            self.message = message
        def __call__(self, form, field):
            pwd = field.data
            if pwd != '123':
                raise ValidationError(self.message)
    
    
    class LoginForm(Form):
        username = simple.StringField(
            label='用户名',
            validators=[validators.DataRequired(message='用户名不能为空'), ]
        )
        # 自定义验证器, 函数的写法
        def validate_username(form, field):
            if field.data != 'tom':
                raise ValidationError('用户名错误')
        password = simple.PasswordField(
            label='密码',
            validators=[
                validators.DataRequired(message='密码不能为空'),
                validators.Length(min=1, max=10, message='密码长度不正确'),
                pwd_validator('密码必须是123'),
    
            ]
        )
        sub = simple.SubmitField(
            label='登陆',
            render_kw={'class': 'red'}
        )

    cbv中运用

    class Login(views.MethodView):
        def get(self):
            form_obj = LoginForm()
            return render_template("login.html", form_obj=form_obj)
        def post(self):
            dic = request.form.to_dict()
            username = dic.get('username')
            password = dic.get('password')
    # if username == 'tom' and password == '123': login_data = LoginForm(request.form) if login_data.validate(): # print(login_data.data) session['user'] = dic['username'] s = session.get('user') return '登陆成功 session是{}'.format(s) else: return render_template('login.html', form_obj=login_data)

  • 相关阅读:
    P3507 [POI2010]GRA-The Minima Game
    P2038 无线网络发射器选址
    2017.9.23清北第二场
    P3183 [HAOI2016]食物链
    2017.9.17校内noip模拟赛解题报告
    Day2代码
    P1328 生活大爆炸版石头剪刀布
    Fibinary Numbers
    Mac os 进行Android开发笔记(1)
    python中文注释及输出出错
  • 原文地址:https://www.cnblogs.com/robertx/p/10692665.html
Copyright © 2020-2023  润新知