Django_Form:正則表達式
1.class TeacherNewForm(Form):數據庫
username = fields.CharField(json
required=True,ui
error_messages={'required': '用戶名不能爲空'},spa
widget=widgets.TextInput(attrs={'placeholder': '用戶名', 'class': 'form-control'})orm
) # 不能爲空中間件
password = fields.CharField(required=True, error_messages={'required': '密碼不能爲空'},繼承
widget=widgets.TextInput(attrs={'placeholder': '密碼', 'class': 'form-control'})) # 不能爲空ip
email = fields.EmailField(required=True, error_messages={'required': '郵箱不能爲空', 'invalid': '郵箱格式錯誤'},get
widget=widgets.EmailInput(
attrs={'placeholder': '郵箱', 'class': 'form-control'})) # 不能爲空,且郵箱格式
cls_list = fields.MultipleChoiceField(choices=[])
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['cls_list'].choices = models.ClassList.objects.values_list('id','caption')
2.# 顯示input,而且將數據庫中的默認值填寫到input框中
form = TeacherForm(initial={'username':obj.username,'password':obj.password,'email':obj.email})
3.class DiyForm(forms.Form):
# 類中建立字段 例如 IntegerField包含了正則表達式
user = fields.CharField(
max_length=18,
min_length=6,
required=True,
error_messages={
'max_length': '用戶名過長',
'min_length': '用戶名太短',
'required': '用戶名不能爲空',
'invalid': '輸入類型錯誤'
}
)
4.import uuid
data = uuid.uuid4() '16fd2706-8baf-433b-82eb-8c7fada847da'
5.# 多選checkbox,值爲列表
user = fields.MultipleChoiceField(
initial=[2, ],
choices=((1, '上海'), (2, '北京'),),
widget=widgets.CheckboxSelectMultiple
6.class FInfo(forms.Form):#從數據庫實時獲取數據
authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())
推薦使用:必須使用values_list,放回元組的類型[(1,"講師"),(2,"班主任"),(3,"管理員")]
classteacher_id = fields.ChoiceField(choices=[])
def __init__(self,*args,**kwargs): #重寫init方法,時時更新
super().__init__(*args,**kwargs) #繼承父類
self.fields["classteacher_id"].choices = models.UserInfo.objects.filter(ut_id = settings.ROLE_CLASSTEACHER).values_list('id', "username")
7.自定義校驗
.class MyForm(Form):
phone = fields.CharField(
validators=[RegexValidator(r'^[0-9]+$', '請輸入數字'), RegexValidator(r'^188[0-9]+{9}$', '數字必須以188開頭')],
.def mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
if not mobile_re.match(value):
raise ValidationError('手機號碼格式錯誤')
phone = fields.CharField(validators=[mobile_validate, ],
error_messages={'required': '手機不能爲空'},
widget=widgets.TextInput(attrs={'class': "form-control",
'placeholder': u'手機號碼'}))
8.clean_field:#在form驗證完後驗證相對應的字段
def clean_user(self): #必須有返回值,只能拿當前字段
"""
Form中字段中定義的格式匹配完以後,執行此方法進行驗證
:return:
"""
v = self.cleaned_data['user']
if models.UserInfo.objects.filter(user=v).count():
raise ValidationError('此用戶名已經存在')
return v
9.clean:#驗證全部字段
#設置總體錯誤,能夠用來設置多個字段總體驗證
def clean(self):
value_dict=self.cleaned_data
v1 = value_dict.get('username')
v2 = value_dict.get('user_id')
if v1=='root' and v2==0:
raise ValidationError('總體錯誤信息')
return self.cleaned_data
10.中間件:
請求 ->process_request1 ->process_request3 ->process_view1 ->process_view3 ->視圖view
->prcess_exception3 ->prcess_exception1 ->process_response3 ->process_response1 ->請求
class Md2(MiddlewareMixin):
def process_request(self,request):
print("Md2請求")
# return HttpResponse("Md2中斷")
def process_response(self,request,response):
print("Md2返回")
return response
def process_view(self, request, callback, callback_args, callback_kwargs):
print("md2 process_view...")
def process_exception(self):
print("md1 process_exception...")
11.認證使用
form = TeacherForm(initial={"username":obj.username,"password":obj.password,"email":obj.email,
"teacher_classes":[obj.id for obj in obj.teacher_classes.all()]}) #帶有初始化的Form
from = TeacherForm(dat = request.POST)
from.is_valid()
from.cleaned_data#一個列表
form.as_json()
from.errors #一個列表
- 主動向form中添加錯誤信息
# form.add_error('password','用戶名或密碼錯誤')
form.add_error('password',ValidationError('用戶名或密碼錯誤'))
這兩個均可以,建議用第二個