就是一個類,能夠校驗字段(前臺傳過來的字段) -怎麼用:
模型:models.py class UserInfo(models.Model): # 寫一個類,要校驗那些字段,就是類的屬性 name=models.CharField(max_length=32) # 定義一個屬性,能夠用來校驗字符串類型 pwd=models.CharField(max_length=32) email=models.EmailField()
模板文件裏:css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <div> <label for="user">用戶名</label> <p><input type="text" name="name" id="name"></p> </div> <div> <label for="pwd">密碼</label> <p><input type="password" name="pwd" id="pwd"></p> </div> <div> <label for="r_pwd">確認密碼</label> <p><input type="password" name="r_pwd" id="r_pwd"></p> </div> <div> <label for="email">郵箱</label> <p><input type="text" name="email" id="email"></p> </div> <input type="submit"> </form> </body> </html>
視圖函數裏:html
# forms組件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) #控制input輸入框的格式,括號裏面是控制的樣式 wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) #控制密碼框,這樣密碼就是密文格式 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(): #判斷is_valid若是是true,校驗成功 print(form.cleaned_data) # 全部乾淨的字段以及對應的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校驗錯誤的字段":["錯誤信息",]} print(form.errors.get("name")) # ErrorList ["錯誤信息",] return HttpResponse("OK") form=UserForm() return render(request,"register.html",locals()) -注意:校驗的字段,能夠多,可是不能少
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <h3>註冊頁面</h3> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <form action="" method="post"> {% csrf_token %} <div> <label for="">用戶名</label> {{ form.name }} </div> <div> <label for="">密碼</label> {{ form.pwd }} </div> <div> <label for="">確認密碼</label> {{ form.r_pwd }} </div> <div> <label for=""> 郵箱</label> {{ form.email }} </div> <input type="submit" class="btn btn-default pull-right"> </form> </div> </div> </div> </body> </html>
<h1>第二種方式(for循環form對象,建議用這種)</h1> <form action="" method="post" > {% for foo in myform %} <p>{{ foo.label }}:{{ foo }}</p> {% endfor %} <input type="submit" value="提交"> </form>
<h1>第三種方式(不建議用)</h1> <form action="" method="post" > {# {{ myform.as_p }}#} {{ myform.as_ul }} <input type="submit" value="提交"> </form> </body> </html>
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 ["錯誤信息",] return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())
<form action="" method="post" novalidate> {% for foo in myform %} #循環出來的是要校驗的字段 <p>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p> {% endfor %} <input type="submit" value="提交"><span>{{ all_error }}</span> </form>
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError def clean_name(self): val=self.cleaned_data.get("name") ret=UserInfo.objects.filter(name=val) if not ret: return val else: raise ValidationError("該用戶已註冊!") def clean_tel(self): val=self.cleaned_data.get("tel") if len(val)==11: return val else: raise ValidationError("手機號格式錯誤")
def clean(self): #程序能走到該函數,前面校驗已經經過了,因此能夠從cleaned_data中取出密碼和確認密碼 pwd=self.cleaned_data.get('pwd') r_pwd=self.cleaned_data.get('r_pwd') if pwd and r_pwd: if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('兩次密碼不一致') else: return self.cleaned_data