django表單分類html
Form驗證流程前端
注意:jquery
規則中的字段名必須得等於html中name的值ajax
Form表單方法django
form.is_valid():驗證表單數據是否合法json
form.errors:表單的錯誤以字典形式返回(若是有多個錯誤,能夠循環這個字典,而後傳給前端)後端
form.clean_data:獲取表單數據app
form.as_p:將表單渲染成P標籤函數
實例1:實現用戶登陸驗證,若是用戶輸入符合規則就跳轉,不然報錯post
定義urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), ]
定義views.py
from django.shortcuts import render,HttpResponse import json from django import forms # Create your views here. #定義用戶輸入規則 class LoginForm(forms.Form): user = forms.CharField(required=True,error_messages={'required':'用戶名不能爲空'}) pwd = forms.CharField(required=True) def login(request): if request.method == 'POST': result = {'status': False,'message':None} obj = LoginForm(request.POST) #request.POST是獲取用戶前端輸入內容,例如:<QueryDict: {'pwd': ['1111'], 'user': ['11111'], 'undefined': ['提交']}> ret =obj.is_valid() #判斷用戶輸入是否符合上面LoginForm定義的規則,若是符合返回True,不然範圍False(符合規則就是 好比:不能爲空,最大輸入字符爲10個等等) if ret: print(obj.clean()) #obj.clean()方法是獲取用戶輸入內容(例如:{'pwd': '1111', 'user': '11111'}) result['status'] = True #若是符合規則置爲true else: print(obj.errors) #obj.errors是獲取用戶輸入的錯誤信息,好比說規則裏定義了不能爲空,可是用戶輸入爲空了,就會報錯(例如:<li>pwd<ul class="errorlist"><li>This field is required.</li></ul>) error_str = obj.errors.as_json() #也能夠將錯誤信息輸出爲json格式,例如:{"pwd": [{"code": "required", "message": "This field is required."}]} print('aaaaaaa',error_str) #這行沒用,用來標記的 result['message'] = json.loads(error_str) #若是不符合規則就把錯誤信息寫到字典裏(例如:{'status': False,'message':{"pwd": [{"code": "required", "message": "This field is required."}]}}) print('bbbbbb',result) #這行沒用,用來作標記的 return HttpResponse(json.dumps(result)) #最後把result字典傳給前端ajax return render(request,'login.html')
定義login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> . error-message { color: red; } </style> </head> <body> <div> <input type="text" name="user"/> </div> <div> <input type="password" name="pwd"/> </div> <input type="button" value="提交" onclick="SubmitForm()"/> <script src="/static/jquery.min.js"></script> <script> function SubmitForm() { var input_dict = {}; $('input').each(function () { var v = $(this).val(); var n = $(this).attr('name'); input_dict[n] = v; }); $.ajax({ url: '/login/', type: 'POST', data: input_dict, dataType: 'json', success: function (callback) { #後端處理完數據返回數據後執行success這部分函數,callback是形參,意思是接收一個參數(接收的數據格式例如:{'status': False,'message':{'pwd': [{'message': 'This field is required.', 'code': 'required'}]}}) if(callback.status){ #若是status=true就跳轉 location.href = '/index'; }else{ #若是status=FALSE $.each(callback.message,function (k,v) { #callback.message就是{'pwd': [{'message': 'This field is required.', 'code': 'required'}]},而後把key賦值給function的k,把vulue賦值給function的value,key就是pwd,value就是列表裏的 var tag = document.createElement('span'); #建立一個span標籤 tag.className = 'error-message'; #給span標籤添加樣式 tag.innerText = v[0].message; #給span標籤賦值,v[0]就獲取到字典的value就是{'message': 'This field is required.', 'code': 'required'}. 而後v[0].message在獲取value,就是This field is required $('input[name="' + k + '"]').after(tag); #而後拼接,獲取input標籤name等於k(這個k就是function傳進來的k,這裏表明pwd),在後邊添加span標籤,加個error-message的樣式,內容爲This field is required }) } } }) } </script>
效果測試
實例2:錯誤信息自定義
定義urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), ]
定義views.py
from django.shortcuts import render,HttpResponse import json from django import forms # Create your views here. #定義用戶輸入規則 class LoginForm(forms.Form): user = forms.CharField(required=True,error_messages={'required':'用戶名不能爲空'}) pwd = forms.CharField(required=True,min_length=6,max_length=10, error_messages={'required':'密碼不能爲空', 'min_length':'最少輸入6位', 'max_length':'最多輸入10位'} ) def login(request): if request.method == 'POST': result = {'status': False,'message':None} obj = LoginForm(request.POST) #request.POST是獲取用戶前端輸入內容,例如:<QueryDict: {'pwd': ['1111'], 'user': ['11111'], 'undefined': ['提交']}> ret =obj.is_valid() #判斷用戶輸入是否符合上面LoginForm定義的規則,若是符合返回True,不然範圍False(符合規則就是 好比:不能爲空,最大輸入字符爲10個等等) if ret: print(obj.clean()) #obj.clean()方法是獲取用戶輸入內容(例如:{'pwd': '1111', 'user': '11111'}) result['status'] = True #若是符合規則置爲true else: print(obj.errors) #obj.errors是獲取用戶輸入的錯誤信息,好比說規則裏定義了不能爲空,可是用戶輸入爲空了,就會報錯(例如:<li>pwd<ul class="errorlist"><li>This field is required.</li></ul>) error_str = obj.errors.as_json() #也能夠將錯誤信息輸出爲json格式,例如:{"pwd": [{"code": "required", "message": "This field is required."}]} print('aaaaaaa',error_str) #這行沒用,用來標記的 result['message'] = json.loads(error_str) #若是不符合規則就把錯誤信息寫到字典裏(例如:{'status': False,'message':{"pwd": [{"code": "required", "message": "This field is required."}]}}) print('bbbbbb',result) #這行沒用,用來作標記的 return HttpResponse(json.dumps(result)) #最後把result字典傳給前端ajax return render(request,'login.html')
定義login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> . error-message { color: red; } </style> </head> <body> <div> <input type="text" name="user"/> </div> <div> <input type="password" name="pwd"/> </div> <input type="button" value="提交" onclick="SubmitForm()"/> <script src="/static/jquery.min.js"></script> <script> function SubmitForm() { var input_dict = {}; $('input').each(function () { var v = $(this).val(); var n = $(this).attr('name'); input_dict[n] = v; }); $.ajax({ url: '/login/', type: 'POST', data: input_dict, dataType: 'json', success: function (callback) { #後端處理完數據返回數據後執行success這部分函數,callback是形參,意思是接收一個參數(接收的數據格式例如:{'status': False,'message':{'pwd': [{'message': 'This field is required.', 'code': 'required'}]}}) if(callback.status){ #若是status=true就跳轉 location.href = '/index'; }else{ #若是status=FALSE $.each(callback.message,function (k,v) { #callback.message就是{'pwd': [{'message': 'This field is required.', 'code': 'required'}]},而後把key賦值給function的k,把vulue賦值給function的value,key就是pwd,value就是列表裏的 var tag = document.createElement('span'); #建立一個span標籤 tag.className = 'error-message'; #給span標籤添加樣式 tag.innerText = v[0].message; #給span標籤賦值,v[0]就獲取到字典的value就是{'message': 'This field is required.', 'code': 'required'}. 而後v[0].message在獲取value,就是This field is required $('input[name="' + k + '"]').after(tag); #而後拼接,獲取input標籤name等於k(這個k就是function傳進來的k,這裏表明pwd),在後邊添加span標籤,加個error-message的樣式,內容爲This field is required }) } } }) } </script>
測試
有時候表單form字段和model字段是一一對應的,所以分別定義form類model類比較麻煩,modelform就是根據model的字段生成form字段
實例一:modelForm驗證
定義models.py
class userAsk(models.Model): '''用戶諮詢,頁面中間部分 我要學習 表單提交''' name = models.CharField(max_length=20,verbose_name='姓名') mobile = models.CharField(max_length=11,verbose_name='手機') course_name = models.CharField(max_length=50,verbose_name='課程名稱') add_time = models.DateTimeField(default=datetime.now,verbose_name='添加時間') class Meta: verbose_name = '用戶諮詢' verbose_name_plural = '用戶諮詢'
定義forms.py
from django import forms from operation.models import userAsk import re class UserAskForm(forms.ModelForm): class Meta: model = userAsk fields = ['name','mobile','course_name'] def clean_mobile(self): #自定義mobile字段的驗證,必須得這麼寫(定義name字段就是clean_name) #獲取mobile字段內容 mobile = self.cleaned_data['mobile'] #定義驗證規則 p = re.compile('^0\d{2,3}\d{7,8}$|^1[358]\d{9}$|^147\d{8}') #把獲取到的mobile字段進行驗證 #若是驗證經過 if p.match(mobile): # 這裏還能返回外鍵 return mobile #若是驗證失敗,這個錯誤信息能夠經過.errors獲取 else: raise forms.ValidationError('mobile error', code='mobile_inval')
定義views.py
from .forms import * import json class AddUserAsk(View): def post(self,request): ret = {'status':False,'msg':None} user_ask_form = UserAskForm(request.POST) if user_ask_form.is_valid(): user_ask_form.save(commit=True) ret['status'] = True return HttpResponse(json.dumps(ret),content_type="application/json") else: ret['status'] = False ret['msg'] = '請確認信息填寫正確' return HttpResponse(json.dumps(ret),content_type="application/json")
定義html
<div class="right companyright"> <div class="head">我要學習</div> <form class="rightform" id="jsStayForm"> <div> <img src="{% static 'images/rightform1.png' %}"/> <input type="text" name="name" id="companyName" placeholder="名字" maxlength="25" /> </div> <div> <img src="{% static 'images/rightform2.png' %}"/> <input type="text" name="mobile" id="companyMobile" placeholder="聯繫電話"/> </div> <div> <img src="{% static 'images/rightform3.png' %}"/> <input type="text" name="course_name" id="companyAddress" placeholder="課程名" maxlength="50" /> </div> <p class="error company-tips" id="jsCompanyTips"></p> <input class="btn" type="button" value="當即諮詢" onclick="SubmitForm()"/> {% csrf_token %} </form> </div> <script> function SubmitForm() { $.ajax({ type: 'POST', url: "{% url 'org:add_ask' %}", data:$('#jsStayForm').serialize(), success: function (callback) { if (callback['status']) { alert('提交成功') } else { $('#jsCompanyTips').html(callback['msg']) } } }) } </script>