1. 程式人生 > >django form表單驗證

django form表單驗證

錯誤 mail 定義 lap hide else ren end blog

簡單例子:

技術分享
 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]
/* */} 22 print(obj.cleaned_data) 23 else: 24 #打印錯誤字段 25 #如:<ul class="errorlist"><li>pwd<ul class="errorlist"><li>最小4位</li></ul></li></ul> 26 #返回json格式錯誤:obj.errors.as_json() 27 #
{"pwd": [{"message": "\u6700\u5c0f4\u4f4d", "code": "min_length"}]} 28 print(obj.errors) 29 return HttpResponse("ok") views.py 技術分享
 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表單驗證