• 框架----Django之Form提交验证(一)


    一、Form提交验证与Ajax提交验证的运用实例

    Form表单提交时会刷新页面,输入失败时,输入框内内容也会随之刷新不能保留;而Ajax提交是在后台偷偷提交,不会刷新页面,因此也就可以保留页面输入框内的内容。

    1. 浏览器访问

    http://127.0.0.1:8000/login/
    
    http://127.0.0.1:8000/register/

    2. urls

    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),
        url(r'^ajax_login/', views.ajax_login),
        url(r'^test/', views.test),
        url(r'^register/', views.register),
    ]

    3. views

    from django.shortcuts import render,redirect,HttpResponse
    from django.forms import Form
    from django.forms import fields
    from django.forms import widgets
    导入模块
      1 class LoginForm(Form):
      2     user = fields.CharField(required=True)
      3     pwd = fields.CharField(min_length=18)
      4 
      5 
      6 def login(request):           
      7     """
      8     obj = xxx(request.POST)
      9     # 是否校验成功
     10     v = obj.is_valid()
     11     # html标签name属性 = Form类字段名
     12 
     13     # 所有错误信息
     14     obj.errors
     15 
     16     # 正确信息
     17     obj.cleaned_data
     18     """
     19     if request.method == 'GET':
     20         return render(request,'login.html')
     21     else:
     22         obj = LoginForm(request.POST)
     23     """
     24     1.LoginForm实例化时,
     25         self.fields={
     26             'user':正则表达式
     27             'pwd':正则表达式
     28         }
     29     2.循环self.fields
     30         flag = True
     31         errors
     32         cleaned_data
     33         for k,v in self.field.items():
     34             #1.user,正则表达式
     35             input_value = request.POST.get(k)
     36             正则表达式和input_value
     37             flag = False
     38         :return flag
     39     """
     40     if obj.is_valid():
     41         print(obj.cleaned_data)    #拿到正确信息
     42         return redirect('http://www.baidu.com')
     43     return render(request,'login.html',{'obj': obj})        #拿到错误信息返回login.html(带着错误信息一起)
     44 
     45 
     46 
     47 def ajax_login(request):        
     48     import json
     49     ret = {'status': True,'msg': None}
     50     obj = LoginForm(request.POST)
     51     if obj.is_valid():
     52         print(obj.cleaned_data)
     53     else:
     54         # print(obj.errors) # obj.errors对象    #拿到错误信息
     55         ret['status'] = False
     56         ret['msg'] = obj.errors
     57     v = json.dumps(ret)
     58     return HttpResponse(v)
     59 
     60 
     61 
     62 
     63 class TestForm(Form):
     64     t1 = fields.CharField(required=True,max_length=8,min_length=2,
     65         error_messages={
     66             'required': '不能为空',
     67             'max_length': '太长',
     68             'min_length': '太短',
     69         }
     70     )
     71     t2 = fields.EmailField()
     72 
     73 def test(request):
     74     if request.method == "GET":
     75         obj = TestForm()
     76         return render(request,'test.html',{'obj': obj})
     77     else:
     78         obj = TestForm(request.POST)
     79         if obj.is_valid():
     80             print(obj.cleaned_data)
     81         else:
     82             print(obj.errors)
     83         return render(request,'test.html',{'obj':obj})
     84 
     85 
     86 
     87 class RegiterForm(Form):
     88     user = fields.CharField(min_length=8)
     89     email = fields.EmailField()
     90     password = fields.CharField()
     91     phone = fields.RegexField('139d+')
     92 
     93 
     94 def register(request):
     95     if request.method == 'GET':
     96         obj = RegiterForm()
     97         return render(request,'register.html',{'obj':obj})
     98     else:
     99         obj = RegiterForm(request.POST)
    100         if obj.is_valid():
    101             print(obj.cleaned_data)
    102         else:
    103             print(obj.errors)
    104         return render(request,'register.html',{'obj':obj})
    views

    4. templates

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title></title>
     6 </head>
     7 <body>
     8     <h1>用户登录</h1>
     9     <form id="f1" action="/login/" method="POST">
    10         {% csrf_token %}
    11         <p>
    12             <input type="text" name="user" />{{ obj.errors.user.0 }}
    13         </p>
    14         <p>
    15             <input type="password" name="pwd" />{{ obj.errors.pwd.0 }}
    16         </p>
    17         <input type="submit" value="提交" />
    18         <a onclick="submitForm();">提交</a>
    19     </form>
    20     <script src="/static/jquery-3.2.1.js"></script>
    21 {#    ajax提交时在后台偷偷提交,不会刷新页面,这也就保留了输入框内的数据#}
    22     <script>
    23         function submitForm(){
    24             $('.c1').remove();
    25             $.ajax({
    26                 url: '/ajax_login/',
    27                 type: 'POST',
    28                 data: $('#f1').serialize(),// user=alex&pwd=456&csrftoen=dfdf
    29                 dataType:"JSON",
    30                 success:function(arg){
    31                     console.log(arg);
    32                     if(arg.status){
    33 
    34                     }else{
    35                         $.each(arg.msg,function(index,value){
    36                             console.log(index,value);
    37                             var tag = document.createElement('span');
    38                             tag.innerHTML = value[0];
    39                             tag.className = 'c1';
    40                             $('#f1').find('input[name="'+ index +'"]').after(tag);
    41                         })
    42                     }
    43                 }
    44             })
    45         }
    46     </script>
    47 </body>
    48 </html>
    login
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title></title>
     6 </head>
     7 <body>
     8 
     9     <form action="/register/" method="POST" novalidate>           {# novalidate  提交表单时让浏览器不对其进行验证 #}
    10         {% csrf_token %}
    11         <p>
    12             {{ obj.user }} {{ obj.errors.user.0 }}
    13         </p>
    14         <p>
    15             {{ obj.email }} {{ obj.errors.email.0 }}
    16         </p>
    17         <p>
    18             {{ obj.password }} {{ obj.errors.password.0 }}
    19         </p>
    20         <p>
    21             {{ obj.phone }} {{ obj.errors.phone.0 }}
    22         </p>
    23         <input type="submit" value="提交"  />
    24     </form>
    25 </body>
    26 </html>
    register
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title></title>
     6 </head>
     7 <body>
     8     <form action="/test/" method="POST" novalidate>
     9         {% csrf_token %}
    10         <p>
    11             {{ obj.t1 }}{{ obj.errors.t1.0 }}
    12         </p>
    13         <p>
    14             {{ obj.t2 }}{{ obj.errors.t2.0 }}
    15         </p>
    16         <input type="submit" value="提交" />
    17     </form>
    18 </body>
    19 </html>
    test

    5. 运行显示截图

  • 相关阅读:
    php第九节课
    php第八节课
    php第七节课
    php第六讲
    php第五节课
    php第四节课
    php第三节课
    Golang Slice切片
    Golang 反射
    Golang 流程控制
  • 原文地址:https://www.cnblogs.com/wangyongsong/p/7126971.html
Copyright © 2020-2023  润新知