一.校驗字段功能
models.py
classuserinfo(models.model):
name=models.charfield(max_length=32)
pwd=models.charfield(max_length=32)
email=models.emailfield()
tel=models.charfield(max_length=32)
register.html
"en">
檢視函式:register
#forms元件
from django.forms import
widgets
wid_01=widgets.textinput(attrs=)
wid_02=widgets.passwordinput(attrs=)
class
userform(forms.form):
name=forms.charfield(max_length=32,
widget=wid_01
)pwd=forms.charfield(max_length=32,widget=wid_02)
r_pwd=forms.charfield(max_length=32,widget=wid_02)
email=forms.emailfield(widget=wid_01)
tel=forms.charfield(max_length=32,widget=wid_01)
defregister(request):
if request.method=="
post":
form=userform(request.post)
ifform.is_valid():
print(form.cleaned_data) #
所有乾淨的字段以及對應的值
else
:
print(form.cleaned_data) #
print(form.errors) #
errordict :
print(form.errors.get("
name
")) #
errorlist ["錯誤資訊",]
二.渲染標籤功能
1.渲染方式1
"en">class="
container
">
class="
row">
class="
col-md-6 col-lg-offset-3
">
渲染方式2
渲染方式3
三.顯示錯誤與重置輸入資訊功能
檢視
defregister(request):
if request.method=="
post":
form=userform(request.post)
ifform.is_valid():
print(form.cleaned_data) #
所有乾淨的字段以及對應的值
else
:
print(form.cleaned_data) #
print(form.errors) #
errordict :
print(form.errors.get("
name
")) #
errorlist ["錯誤資訊",]
return render(request,"
register.html
",locals())
form=userform()
return render(request,"
register.html
",locals())
模版
四.全域性鉤子和區域性鉤子
模版
#forms元件
from django.forms import
widgets
wid_01=widgets.textinput(attrs=)
wid_02=widgets.passwordinput(attrs=)
from django.core.exceptions import
validationerror
class
userform(forms.form):
name=forms.charfield(max_length=32,
widget=wid_01
)pwd=forms.charfield(max_length=32,widget=wid_02)
r_pwd=forms.charfield(max_length=32,widget=wid_02)
email=forms.emailfield(widget=wid_01)
tel=forms.charfield(max_length=32,widget=wid_01)
#區域性鉤子
defclean_name(self):
val=self.cleaned_data.get("
name")
ifnot
val.isdigit():
return
val
else
:
raise validationerror("
使用者名稱不能是純數字!")
#全域性鉤子
defclean(self):
pwd=self.cleaned_data.get("
pwd"
) r_pwd=self.cleaned_data.get("
r_pwd")
if pwd==r_pwd:
return
self.cleaned_data
else
:
raise validationerror('
兩次密碼不一致!')
defregister(request):
if request.method=="
post":
form=userform(request.post)
ifform.is_valid():
print(form.cleaned_data) #
所有乾淨的字段以及對應的值
else
: clean_error=form.errors.get("
__all__")
return render(request,"
register.html
",locals())
form=userform()
return render(request,"
register.html
",locals())
檢視
django元件 forms元件
針對乙個例項 註冊使用者講解。模型 models.py class userinfo models.model name models.charfield max length 32 pwd models.charfield max length 32 email models.emailfield...
Django元件 forms元件
針對乙個例項 註冊使用者講解。模型 models.py class userinfo models.model name models.charfield max length 32 pwd models.charfield max length 32 email models.emailfield...
Django的forms元件使用
models.py class userinfo models.model name models.charfield max length 32 pwd models.charfield max length 32 email models.emailfield 模板檔案 lang en char...