• form表单验证字段学习总结


    字段的属性梳理

    最重要的字段

    required

    inital

    widget

    error_messages

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    required:是否允许为空

    class my_forms_field(forms.Form):
        f1 = fields.CharField(
            required=True,
    
        )
    

        

    默认required是True,也就是不允许为空

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    widget:指定插件

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    lable:设置一个label标签,我们之前会在input标签之前写一个label标签,这个label标签有一个for的属性,指向后面的input标签,只要点击一下lable标签的内容,则鼠标会自动跳转到input标签中

    form表单的代码

    user4 = forms.CharField(required=True,label="用户名",widget=widgets.TextInput(attrs={"placeholder":"密码"}))
    

      

    前端的代码,第一个lable标签实现的效果就和obj.user4.label_tag的效果一样,会生成一个lable标签,有for的属性

            <p>
                <label for="{{ obj.user4.id_for_label }}">{{ obj.user4.label }}</label>

           用下面2段代码就可以实现label标签的效果了,上面的代码只是另外一种写法 {{ obj.user4.label_tag }} {{ obj.user4 }} </p>

    html的代码

    浏览器的效果

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

      

    initail:初始值

    user4 = forms.CharField(required=True,initial="老鼠",label="用户名",widget=widgets.TextInput(attrs={"placeholder":"密码"}))
    

      

      ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    help_text生成一个帮助信息

    user4 = forms.CharField(required=True,initial="老鼠",label="用户名",widget=widgets.TextInput(attrs={"placeholder":"密码"}),help_text="aaaa")
    

      

            <p>
                <label for="{{ obj.user4.id_for_label }}">{{ obj.user4.label }}</label>
                {{ obj.user4.label_tag }}
                {{ obj.user4 }}
                {{ obj.user4.help_text }}
            </p>
    

      

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     show_hidden_initail:是否生成一个有默认值的隐藏的标签,主要的实际用户就是判断客户当前的输入和默认值是否一样

        user4 = forms.CharField(required=True,
                                initial="老鼠",
                                label="用户名",
                                widget=widgets.TextInput(attrs={"placeholder":"密码"}),
                                help_text="aaaa",
                                show_hidden_initial=True)
    

      

    html代码不需要做任何修改

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     自定义匹配规则

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     disable:标签是否允许编辑

        user4 = forms.CharField(required=True,
                                initial="老鼠",
                                label="用户名",
                                widget=widgets.TextInput(attrs={"placeholder":"密码"}),
                                help_text="aaaa",
                                show_hidden_initial=True,
                                disabled=True)
    

      

    前端页面

      ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    localize:本地化,暂时不涉及

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    label_suffix设置lable标签和input标签之间的字符,默认是用冒号,通过label_suffix可以替换冒号,设置成我们想要的符号

        user4 = forms.CharField(required=True,
                                initial="老鼠",
                                label="用户名",
                                widget=widgets.TextInput(attrs={"placeholder":"密码"}),
                                help_text="aaaa",
                                show_hidden_initial=True,
                                disabled=True,
                                label_suffix="---->")
    

      

      ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     error_messages:设置不同的错误码对应不同的报错

        u_name = forms.CharField(min_length=6,max_length=12,error_messages={"required":"用户名不能为空",
                                                                            "min_length":"最小长度为6",
                                                                            "max_length":"最大长度为12"
                                                                            
    

      


     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    max_length:最大长度

    min_length:最小长度

    min_value:最小值

    max_value:最大值

    可以根据上面4个在error_messages中当做错误码

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    srtip=true:是否移除空白

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    日期格式

     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    choice:默认是select框

        user5 = forms.ChoiceField(
            initial=1,
            choices=[(1,"找死"),(2,"刘能"),(3,"六大脑袋")]
        )
    

      

    且默认选中第一个,前台选中,后台拿到的字符串


     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     如果想要实现字符类型的转换可以有下面两种方法

    这个只能转换为数字

        user7 = forms.IntegerField(
            initial=1,
            choices=[(1, "找死"), (2, "刘能"), (3, "六大脑袋")]
        )
    

     

    这个可以根据函数自定义转换后的类型,这里这个x就是select框中选中的1,或者2,或者3

        user6 = forms.TypedChoiceField(
            coerce=lambda x:int(x),
            initial=1,
            choices=[(1, "找死"), (2, "刘能"), (3, "六大脑袋")]
        )
    

      

     


     ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    from django import forms
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator
    # 自定义规则需要引入的模块
    
    
    class my_first_forms_example(forms.Form):
        u = forms.CharField()
        # input type='text'
        e = forms.EmailField()
        # input type='email'
        p = forms.PasswordInput()
        # input type='password'
    
    # 类;
    #     1、创建form标签
    #     2、验证的哪些字段
    #
    # 字段:
    #     用于验证某个字段的
    #
    # 插件:
    #     生成具体的标签,用widget来指定
    # user = forms.CharField(..,widget=Input框
    
    class my_first_forms(forms.Form):
        u1 = forms.CharField(widget=forms.PasswordInput)
        u2 = forms.CharField(widget=forms.TextInput)
        u3 = forms.CharField(widget=forms.TextInput(attrs={"class":"c1","placeholder":"用户名"}))
        u4 = forms.IntegerField()
        # 后端拿到的数据是数字
    
    
        u5 = forms.ChoiceField(initial=3,choices=[(1,"上海1"),(2,"北京1"),(3,"深圳1")])
        # 后台拿到的数据是字符串"1"或者"2"或者"3"
    
    
    
        u6 = forms.CharField(initial=3,widget=forms.Select(choices=[(1, "上海2"), (2, "北京2"), (3, "深圳2")]))
        # 后台拿到的数据是字符串"1"或者"2"或者"3"
    
    # 前台通过form标签提交给后台的数据全部都是字符串,我们通过form还可以实现字符串转换为数字,也就是类型转换的作用
    
    
    
        u7 = forms.IntegerField(initial=3,widget=forms.Select(choices=[(1, "上海3"), (2, "北京3"), (3, "深圳3")]))
        # 后台拿到的是数字1、2、3
    
        u8 = forms.CharField(widget=forms.RadioSelect(choices=[(1, "上海3"), (2, "北京3"), (3, "深圳3")]))
        # 后台拿到的数据是字符串"1"或者"2"或者"3"
    
        u9 = forms.CharField(widget=forms.CheckboxSelectMultiple(choices=[(1, "上海3"), (2, "北京3"), (3, "深圳3")]))
    
    
    # 由于form有3个不方面组成,类,字段,插件
    # 下面我们我们专门来说字段
    
    class my_forms_field(forms.Form):
        f1 = fields.CharField(
            # required=True,默认值
            required=False,
    
            label="用户名",
    
            label_suffix="--->",
    
            initial="崔皓然",
    
            help_text="这是一个帮助信息",
    
            show_hidden_initial=True,
    
            validators=[RegexValidator(r'^d+',"请输入数字",code="111"),RegexValidator(r'^139d{8}$',"必须要以139开头",code="222")],
            # 上面我们自定义了code,如果我们定义了code,则在error_messages可以根据不同的code报不同的错误,也可以不写code,不满足第一个正则,报第一个正则里的报错,
            # 不满足第二个正则,报第二个正则里的报错,如果没有设置code,则默认的code的类型是invalid,且error_messages中定义的报错优先级高
    
            error_messages={"required": "不允许为空", "222": "2222222222", "111": "11111111111111111111"},
    
            # disabled=True,默认值
            disabled=False,
    
            max_length=12,
            min_length=6,
    
            # strip=True,是否移除空白,默认值是true
            strip=False,
        )
    
        f2 = fields.IntegerField(
            max_value=100,
            min_value=20,
        )
        f3 = fields.FloatField(
            max_value=100,
            min_value=20,
    
        )
    
        f4 = fields.DecimalField(
            # 十进制的小数
    
            max_value=100,
            min_value=20,
            max_digits=10,
            # 总长度
    
            decimal_places=3
            # 小数位的长度
        )
        f5 = fields.EmailField()
    
        f6 = fields.FileField()
    
        f7 = fields.ImageField()
    
        f8 = fields.ChoiceField(
            choices=[(1, "上海3"), (2, "北京3"), (3, "深圳3")],
            initial=3,
            required=True,
            label="城市",
            label_suffix="------>"
        )
    
        f9 = fields.TypedChoiceField(
            choices=[(1, "上海4"), (2, "北京4"), (3, "深圳4")],
            initial=3,
            required=True,
            coerce=lambda x:int(x)
        )
    
        f10 = fields.MultipleChoiceField(
            choices=[(1, "上海5"), (2, "北京5"), (3, "深圳5")],
            initial=[1,3,]
        )
    
        f11 = fields.TypedMultipleChoiceField(
            choices=[(1, "上海5"), (2, "北京5"), (3, "深圳5")],
            initial=[1, 3, ],
            coerce=lambda x:int(x),
        )
    

      

    f12 = fields.FilePathField(path="app1",allow_folders=True,recursive=False,allow_files=)
    
    # recursive:递归显示,true不显示,false显示
    # allow_folders:是否显示文件夹
    # allow_files:是否显示文件
    
        f13 = fields.GenericIPAddressField(
            protocol="both"
        )
    
        f14 = fields.SlugField()
        # 只允许数字,字母,下划线,减号
    

      

    插件的学习

     

     

    我们在看一个例子,比如我们编辑一个东西,那么在弹出的框中需要有我们的内容,那么这个内容怎么来的,其实这个需要从数据库中获取,比如下面的例子,我们拿到一个字段的id,通过id在拿到名称,然后在通过model去数据库中拿到值,在返回给前端

    form的代码,这个纯属复习

    class myforms2(forms.Form):
        u = fields.CharField(
            label="用户名",
            strip=True,
            max_length=20,
            min_length=10,
            required=True,
            validators=[RegexValidator(r'^a.*y$',code="error1")],
            error_messages={"required":"不允许为空","error1":"必须以a开头,y结尾","max_length":"最大长度是20","min_length":"最小长度是10"},
            widget=forms.TextInput(attrs={"class":"c1"}),
            label_suffix="------>"
        )
    

      

    在看视图函数的代码

    def my_forms2(request):
        method = request.method.lower()
        if method == "get":
            nid = int(request.GET.get("nid","1"))
    
            user_obj = models.teacher.objects.get(id=nid)
            u_dict = {"u":user_obj.teacher_name}
            form_obj = myforms.myforms2(u_dict)
         给form表单对象传值,然后将传递的值渲染到前端上 return render(request,"my_forms2.html",{"obj":form_obj}) else: form_obj = myforms.myforms2(request.POST,request.FILES) if form_obj.is_valid(): new_teacher_name = request.POST.get("u") nid = int(request.GET.get("nid")) models.teacher.objects.filter(id=nid).update(teacher_name=new_teacher_name) return redirect("/app1/my_forms2/") else: return render(request,"my_forms2.html",{"obj":form_obj})

      

    最后在看下html的代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/css/css3.css">
    </head>
    <body>
        <form action="/app1/my_forms2/?nid=1" method="post">
            <p>{{ obj.u.label_tag }}{{ obj.u }}</p>
            <span>{{ obj.u.errors.0 }}</span>
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    

      

  • 相关阅读:
    Spoj 2798 Qtree3
    [HAOI2015]树上操作
    Grass Planting
    [ZJOI2008] 树的统计Count
    Spoj375 Qtree--树链剖分
    [HNOI2012]永无乡
    雨天的尾巴
    temp
    线段树动态开点之逆序对
    线段树动态开点
  • 原文地址:https://www.cnblogs.com/bainianminguo/p/9206672.html
Copyright © 2020-2023  润新知