python之路 自定義forms元件

2022-04-10 14:49:55 字數 3138 閱讀 9373

import

reimport

copy

class

validateerror(exception):

def__init__

(self,detail):

self.detail =detail

####################### 外掛程式

class

textinput(object):

def__str__

(self):

return""

class

emailinput(object):

def__str__

(self):

return""

####################### 內部包含正則,用於驗證

class

field(object):

def__init__(self,required=true,error_messages=none,widget=none):

self.required =required

self.error_messages =error_messages

ifnot

widget:

self.widget =textinput()

else

: self.widget =widget

def__str__

(self):

return

str(self.widget)

class

charfield(field):

defvalid(self,val):

ifself.required:

ifnot

val:

msg = self.error_messages['

required']

raise

validateerror(msg)

return

valclass

emailfield(field):

reg = "

^\w+@\w+$

"def

valid(self,val):

ifself.required:

ifnot

val:

msg = self.error_messages['

required']

raise

validateerror(msg)

result =re.match(self.reg,val)

ifnot

result:

msg = self.error_messages.get('

invalid

','格式錯誤')

raise

validateerror(msg)

return

val#

###################### form,獲取使用者提交內容+獲取定義的字段物件

class

form(object):

def__init__(self,data=none):

#獲取派生類中的所有靜態字段

#print(self.__class__.__dict__)

self.data =data

self.fields = copy.deepcopy(self.__class__

.declare_field)

self.cleaned_data ={}

self.errors ={}

def__new__(cls, *args, **kwargs):

declare_field ={}

for field_name, field in cls.__dict__

.items():

ifisinstance(field,field):

declare_field[field_name] =field

cls.declare_field =declare_field

return object.__new__

(cls)

defis_valid(self):

#使用者提交的資料

#self.data #

#self.fields #

for field_name,filed in

self.fields.items():

try:

input_val =self.data.get(field_name)

val =filed.valid(input_val)

method = getattr(self,"

cleaned_%s

" %field_name,none)

ifmethod:

val =method(val)

self.cleaned_data[field_name] =val

except

validateerror as e:

self.errors[field_name] =e.detail

return len(self.errors) ==0

def__iter__

(self):

return

iter(self.fields.values())

class

userform(form):

username = charfield(error_messages=,widget=textinput())

pwd = emailfield(error_messages=,widget=emailinput())

################ 應用

obj = userform(data=)

ifobj.is_valid():

print('

驗證成功

',obj.cleaned_data)

else

:

print("

驗證失敗

",obj.errors)

###################### html #####################

for x in

obj:

print(x)

Django自定義form表單

from django import forms class customform forms.form ba forms.integerfield label 數字 widget forms.textinput attrs label引數對應的就是數字a widget表示控制項,input就是乙個...

Tronado自定義Form元件

一 獲取類裡面的靜態屬性以及動態屬性的方法 方式一 方式一 class foo object user 123 def init self self.name 123self.age 456 defaaa self self.name sd obj foo print obj.dict 獲取物件屬性...

element 封裝form整合校驗自定義內容

後台管理系統使用form的頻率非常高,並且存在不同的校驗,如果不加以封裝,大量的ifelse存在,不同人可能寫不同的校驗規則,大大增加了維護的難度。封裝乙個form元件 讓校驗規則全部交由元件處理。封裝好解決了很多需求 記錄並且分享下 接解了校驗,讓校驗由元件來處理,傳入相應校驗規則即可。使用ren...