Form驗證的原理
首先使用者在注冊界面送出表單,背景收到表單之後通過request.post取到資料然後傳入已經寫好的Form類
執行obj.is_valid()這裡的obj為Form的執行個體,在Form類裡面對字段一個一個進行驗證先執行正則比對然後執行clean方法
這裡的clean方法就是一個鈎子,但是不能在驗證某個字段的時候調用其他字段,原因是這個時候其他字段不能确定是否驗證完成了
需要在所有字段驗證之後再執行這個鈎子(clean方法)具體實作方法如下:
________________________________________________views.py______________________________________________________
if request.method == "POST":
check_obj = account.Register(request.POST)
if check_obj.is_valid():
username = check_obj.cleaned_data.get('username') #驗證之後的值存放在check_obj.cleaned_data裡面
password = check_obj.cleaned_data.get('password')
email = check_obj.cleaned_data.get('email')
—————————————————————————————————————————————————Register—————————————————————————————————————————————————————————
from django.forms import fields as ac_fields
from django import forms as ac_forms
from django.core.exceptions import ValidationError
class Register(ac_forms.Form):
username = ac_fields.CharField(error_messages={'required': '使用者名不能為空'})
#password = ac_fields.CharField(error_messages={'required': '密碼不能為空'})
password = ac_fields.RegexField(
'^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[[email protected]#$\%\^\&\*\(\)])[[email protected]#$\%\^\&\*\(\)]{8,32}$', #這裡正則比對驗證要求密碼了裡面包含字母、數字、特殊字元
min_length=12,
max_length=32,
error_messages={'required': '密碼不能為空.',
'invalid': '密碼必須包含數字,字母、特殊字元',
'min_length': "密碼長度不能小于8個字元",
'max_length': "密碼長度不能大于32個字元"}
)
repassword = ac_fields.CharField(error_messages={'required': '确認密碼不能為空'})
email = ac_fields.CharField(error_messages={'required': '郵箱不能為空', 'invalid':'郵箱格式錯誤'})
check_code = ac_fields.CharField(error_messages={'required': '驗證碼不能為空',
'invalid': '郵箱格式錯誤'})
def clean(self):
pwd1 = self.cleaned_data.get('password')
pwd2 = self.cleaned_data.get('repassword')
if pwd1==pwd2:
pass
else:
from django.core.exceptions import ValidationError #這裡異常子產品導入要放在函數裡面,放到檔案開頭有時會報錯,找不到
raise ValidationError('密碼輸入不一緻')
然後驗證之後如果兩次密碼不相同,那麼觸發的ValidationError會放到公共錯誤裡面:
check_obj.errors['__all__'] 或者
check_obj.errors[NON_FIELD_ERRORS]
但是在前端不識别check_obj.errors.__all__,是以前端需要使用:check_obj.non_field_errors(其他正常字段的取法:check_obj.errors.username.0)
知識點補充:
form = trouble_createFrom({'title':obj1.title,'detail':obj1.detail})
form = trouble_createFrom(initial={'title':obj1.title,'detail':obj1.detail})
加initial與不加的差別,加了initial之後Form不做驗證,不會吧錯誤資訊展示到error裡面
v = Trouble.objects.filter(id=nid,status=1).update(**form.cleaned_data)
這裡的v代表的是收影響的行數,若v為0則代表修改沒有生效
在form裡使用日期插件 django.forms.extras.widgets import SelectDateWidge
然後在前端頁面導入
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" target="_blank" rel="external nofollow" />
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css" target="_blank" rel="external nofollow" />
能解決日期插件格式不對齊的問題
轉載于:https://www.cnblogs.com/qiangayz/p/9175808.html