django form表單驗證
簡單例子:
1 #自定義驗證類 2 class Check_form1(forms.Form): 3 #user就是要驗證的字段,這裏對應前端name <input type=‘text‘ name=user> 4 user = fields.CharField() 5 pwd = fields.CharField() 6 email = fields.EmailField() 7 8 9 10 def test_form1(request): 11 if request.method == ‘GET‘: 12 return render(request,‘form1.html‘) 13 14 elif request.method == ‘POST‘: 15 obj = Check_form(request.POST) 16 17 #obj.is_valid()表單驗證,全通過返回True,有錯誤就false 18 result = obj.is_valid() 19 if result: 20 21 #{‘pwd‘: u‘12311‘, ‘user‘: u‘12311‘, ‘email‘: [email protected]
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 <form action="/test_form1/"method="post"> 10 {% csrf_token %} 11 <p> <input type="text" name="user"></p> 12 <p> <input type="text" name="pwd"></p> 13 <p> <input type="text" name="email"></p> 14 <input type="submit" value="提交" /> 15 </form> 16 17 18 </body> 19 </html>html
階級例子:
django form表單驗證