简单例子:
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‘: u‘[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
阶级例子:
时间: 2024-10-12 17:13:19