Django元件 forms元件

2022-08-29 03:57:14 字數 3173 閱讀 2586

針對乙個例項:註冊使用者講解。

模型:models.py

class userinfo(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:

檢視函式: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)

def register(request):

if request.method=="post":

form=userform(request.post)

if form.is_valid():

print(form.cleaned_data) # 所有乾淨的字段以及對應的值

else:

print(form.cleaned_data) #

print(form.errors) # errordict :

print(form.errors.get("name")) # errorlist ["錯誤資訊",]

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)

# 區域性鉤子

def clean_name(self):

val=self.cleaned_data.get("name")

if not val.isdigit():

return val

else:

raise validationerror("使用者名稱不能是純數字!")

# 全域性鉤子

def clean(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('兩次密碼不一致!')

def register(request):

if request.method=="post":

form=userform(request.post)

if form.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 tel mode...

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...