zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    cinder支持nfs快照
    浏览器输入URL到返回页面的全过程
    按需制作最小的本地yum源
    创建可执行bin安装文件
    RPCVersionCapError: Requested message version, 4.17 is incompatible. It needs to be equal in major version and less than or equal in minor version as the specified version cap 4.11.
    惠普IPMI登陆不上
    Linux进程状态——top,ps中看到进程状态D,S,Z的含义
    openstack-neutron基本的网络类型以及分析
    openstack octavia的实现与分析(二)原理,架构与基本流程
    flask上下文流程图
  • 原文地址:https://www.cnblogs.com/robertx/p/10692665.html
Copyright © 2011-2022 走看看