1. 程式人生 > >wtforms-表單生成及驗證

wtforms-表單生成及驗證

arch 屬性 方法 pymysql 我們 request ipad html5 .data

介紹

wtforms是一個支持多個web框架的form組件,主要用來做表單的驗證以及生成的,

安裝

pip install wtforms

使用

自定義一個類,繼承wtforms.Form類,定義字段

from wtforms import Form
from wtforms.fields import simple,core,html5 # 字段來自於這裏
from wtforms import validators # 驗證規則來自於這裏
from wtforms import widgets # 工具是在這裏

class LoginForm(Form):
    user = simple.StringField( 
            label=‘用戶名‘, # 提示信息
            validators=[validators.DataRequired(message=‘用戶名不能為空.‘)], #驗證規則的列表
            widget=widgets.TextInput(), # 優先按他定義的方式渲染input標簽
            render_kw={‘class‘: ‘form-control‘} # 為input標簽設置屬性
    )

渲染

實例自定義的類對象,傳入模板中,如果實例對象時傳入了數據,該數據會被渲染到input框裏

{{ form.name }} # 該字段的input框
{{ form.name.label }} # 該字段提示信息
{{ form.name.errors[0] }} # 該字段的錯誤信息,建議用這種方式,下面那種獲取字段的錯誤信息會拋出異常
{{ form.errors }} # 全部的錯誤信息 

# 也可以使用for循環的方式,並且他的順序不會錯亂,因為Form內部維持了一個計數器
{% for item in form %}
        <p>{{item.label}}: {{item}} {{item.errors[0] }}</p>
{% endfor %}

驗證

實例自定義類對象是傳遞數據

form = LoginForm(formdata=request.form)
if form.validate():
    # 驗證通過,打印數據
    print(form.data)
else:
    print(form.error) # 打印錯誤信息

字段

在wtforms.fields提供了三個包simple,core,html5

simple是簡單常用的包括:

 [‘BooleanField‘, ‘TextAreaField‘, ‘PasswordField‘, ‘FileField‘,
    ‘HiddenField‘, ‘SubmitField‘, ‘TextField‘]

core是不太常用的

(
    ‘BooleanField‘, ‘DecimalField‘, ‘DateField‘, ‘DateTimeField‘, ‘FieldList‘,
    ‘FloatField‘, ‘FormField‘, ‘IntegerField‘, ‘RadioField‘, ‘SelectField‘,
    ‘SelectMultipleField‘, ‘StringField‘,
)

html5中的標簽自帶正則(瀏覽器校驗)

(
    ‘DateField‘, ‘DateTimeField‘, ‘DateTimeLocalField‘, ‘DecimalField‘,
    ‘DecimalRangeField‘, ‘EmailField‘, ‘IntegerField‘, ‘IntegerRangeField‘,
    ‘SearchField‘, ‘TelField‘, ‘URLField‘,
)

  這裏要註意的是core.RadioField(單選),core.SelectField(下拉菜單),core.SelectMultipleField(多選下拉菜單)有一個coerce屬性,指定了數據轉化的類型(因為從前端獲取到的都是字符串),如果沒有轉化成對應的數據類型就會驗證失敗.

另外如果我們想要動態的獲取choices的值,可以通過在自己寫的類中重寫__init__方法.每次實例化的時候去獲去一次,再執行父類中的__init__就可以實時更新選項了

class RegisterForm(Form):
    city = core.SelectField(
        label=‘城市‘,
        choices=SQLHelper.fetch_all(‘select id,name from city‘,{},None),
        coerce=int
    )
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.city.choices = PymysqlConn.fetch_all(‘select id,name from city‘,{},None)

驗證規則

在wtforms.validators中提供了許多的驗證規則

(
    ‘DataRequired‘, ‘data_required‘, ‘Email‘, ‘email‘, ‘EqualTo‘, ‘equal_to‘,
    ‘IPAddress‘, ‘ip_address‘, ‘InputRequired‘, ‘input_required‘, ‘Length‘,
    ‘length‘, ‘NumberRange‘, ‘number_range‘, ‘Optional‘, ‘optional‘,
    ‘Required‘, ‘required‘, ‘Regexp‘, ‘regexp‘, ‘URL‘, ‘url‘, ‘AnyOf‘,
    ‘any_of‘, ‘NoneOf‘, ‘none_of‘, ‘MacAddress‘, ‘mac_address‘, ‘UUID‘
)

下面介紹幾個常用的

DataRequired:非空驗證,message=錯誤信息

Email:郵箱格式驗證,message=錯誤信息

Length: 長度驗證,min=最短,max=最長,message=錯誤信息

Regexp: 正則匹配,regex正則表達式,message=錯誤信息

EqualTo:與其他字段的值比較是否相同,fieldname=其他字段名,message=錯誤信息

自定義驗證-鉤子

# 為一個字段設置驗證
def validate_字段名(self, field):
    print(field.data) # 當前字段傳過來的值
    print(self.data) # 當前傳過來的所有的值:name,gender.....
    if 驗證失敗:
        raise validators.ValidationError("繼續後續驗證") 
        # raise validators.StopValidation("不再繼續後續驗證") 

小部件

wtforms.widgets提供了許多的表單樣式,每個字段都有默認的widget,通過設置widget可以修改渲染出來的樣式

 (‘CheckboxInput‘, ‘FileInput‘, ‘HiddenInput‘, ‘ListWidget‘, ‘PasswordInput‘,
    ‘RadioInput‘, ‘Select‘, ‘SubmitInput‘, ‘TableWidget‘, ‘TextArea‘,
    ‘TextInput‘, ‘Option‘)

多選框的設置

favor = core.SelectMultipleField(
        label=‘喜好‘,
        choices=(
            (1, ‘籃球‘),
            (2, ‘足球‘),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2]
    )

  

wtforms-表單生成及驗證