1. 程式人生 > >Django組件--form表單字段格式校驗

Django組件--form表單字段格式校驗

用戶名 filter 通過 如果 屬性 for bsp 二層 char

forms組件

1、校驗字段功能(最核心功能)

示例1:
在服務端進行格式校驗
-------視圖函數裏--------
from django import forms
class UserForm(forms.Form): #新建一個校驗類
name = forms.CharField(min_length) #必須為字符串,最小4位
email = forms.EmailField() #郵箱校驗

def register(request):
# 字典的鍵必須跟校驗類裏的字段一樣
form=UserForm({"name":"yuan","email":"123"})
# 開始校驗,所有值校驗通過返回True

# 字典裏有多少個無所謂,只要校驗類裏的字段通過就是True
bool = form.is_valid()
# cleaned_data 這裏面放所有校驗通過的鍵值
form.cleaned_data
# errors 這裏面放所有未通過的鍵值 是仿字典類型
#例如name沒通過,要取errors裏的錯誤信息:form.errors["name"][0]
form.errors

return HttpResponse(request, "ok")

示例2:

def register(request):
#校驗類字段要跟前端form表單一樣
form=UserForm(request.POST)

if form.is_valid():
clean = form.cleaned_data
else:
clean = form.cleaned_data
errors = form.errors

總結:
1.前端form表單內的需要校驗的值,要跟後端校驗類的字段一致
2. is_valid() 、 cleaned_data、 errors各自含義

forms組件的渲染標簽功能:
1、渲染方式一
先寫後端校驗類,再在前端渲染,charFiled渲染成input標簽:
class UserForm(forms.Form):
name = forms.CharField(min_length=4)

pwd = forms.CharField(min_length=4)
r_pwd = forms.CharField(min_length=4)
email = forms.EmailField()
tel = forms.CharField()

def reg(request):
form = UserForm()
return render("reg_html",{"form":form})

為了方便,Django可以在前端按照後端寫的校驗類進行渲染
<form>
{% csrf_token %}
用戶名:{{ form.name }}
密碼:{{ form.pwd }}
確認密碼:{{ form.r_pwd }}
郵箱:{{ form.email }}
電話:{{ form.tel }}
<input type="submit">
</form>

2、渲染方式二:如果字段很多
class UserForm(forms.Form):
name = forms.CharField(min_length=4, label="用戶名")
pwd = forms.CharField(min_length=4, label="密碼")
r_pwd = forms.CharField(min_length=4, label="確認密碼")
email = forms.EmailField(label="郵箱")
tel = forms.CharField(label="電話")

def reg(request):
form = UserForm()
return render("reg_html",{"form":form})
-------------------------------
<form>
{% csrf_token %}
{% for field in form%}
<div>
<label for="">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input type="submit">
</form>


3、渲染方式三,自己搞著玩可以
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>


4、渲染錯誤信息
def register(request):
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
clean = form.cleaned_data
else:
clean = form.cleaned_data
errors = form.errors
# 註意:這裏返回的頁面可以保存用戶上次已經填過的數據,還包括錯誤信息
return render("reg_html",{"form":form})

#如果是get請求,渲染空form頁面
form=UserForm()
return render(request,"reg_html",{"form":form})
-----------------
<form>
{% csrf_token %}
{% for field in form%}
<div>
<label for="">{{ field.label }}</label>
{{ field }} <span>{{ field.errors.0 }}</span>
</div>
{% endfor %}
<input type="submit">
</form>
---------------------

form組件--校驗類的參數

改渲染的標簽類型為password:widgets
改錯誤提示信息:error_messages
如果需要給渲染的標簽加樣式類,加屬性鍵值對,什麽都行:widget=widgets.TextInput(attrs={"class":"form-control"})

from django.forms import widgets
class UserForm(forms.Form):
name = forms.CharField(min_length=4, label="用戶名", error_messages={"required":"不能為空","invalid":"格式錯誤"})
pwd = forms.CharField(min_length=4, label="密碼",widget=widgets.PasswordInput(attrs={"class":"form-control"}))
r_pwd = forms.CharField(min_length=4, label="確認密碼")
email = forms.EmailField(label="郵箱",widget=widgets.TextInput(attrs={"class":"form-control"}))
tel = forms.CharField(label="電話")


forms組件校驗的局部鉤子(要看源碼理解)
校驗第二層:clean_xx方法,校驗通過返回該值,否則拋ValidationError異常

from django.core.exceptions import ValidationError
class UserForm(forms.Form):
name = forms.CharField(min_length=4, label="用戶名")
pwd = forms.CharField(min_length=4, label="密碼")
r_pwd = forms.CharField(min_length=4, label="確認密碼")
email = forms.EmailField(label="郵箱")
tel = forms.CharField(label="電話")

#該功能驗證用戶名是否已被註冊
def clean_name(self):
name = self.cleaned_data.get("name")

ret = UserInfo.objects.filter(name=name)
if not ret:
return name
else:
#只能拋這個錯誤
raise ValidationError("該用戶已註冊")

全局鉤子--校驗form表單兩次密碼輸入是否一致:
在校驗類裏,覆蓋父類clean方法

獲取全局鉤子錯誤:form.errors.get("__all__")[0]

def clean():
pwd=self.cleaned_data.get(‘pwd‘)
r_pwd=self.cleaned_data.get(‘r_pwd‘)

if pwd and r_pwd:
# pwd跟r_pwd之前的校驗已通過,才驗證全局鉤子
if pwd==r_pwd:
return self.cleaned_data
else:
raise ValidationError(‘兩次輸入密碼不一致‘)
else:
return self.cleaned_data






Django組件--form表單字段格式校驗