wtforms-表單生成及驗證

介紹

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

安裝

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框裏html5

{{ 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 %}

驗證

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

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

實例化時可傳遞的幾種數據mysql

formdata : request.data這種有get和get_list的
data : 一個字典
obj : obj.字段名得到數據的,好比模型類對象

字段

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

simple是簡單經常使用的包括:正則表達式

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

core是不太經常使用的sql

(
    '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]
    )

源碼中的實例化以及驗證

相關文章
相關標籤/搜索