zoukankan      html  css  js  c++  java
  • Django(Form)

    一. Form 

    #功能:
    #	- 对用户提交的数据进行验证
    #	- 保留上次输入内容
    #	- 生成HTML标签

    #创建Form类时,主要涉及到 字段 和 插件
    #     - 字段用于对用户请求数据的验证
    #     - 插件用于自动生成HTML 

    二. Form 内置字段

    Field
        required=True,               是否允许为空
        widget=None,                 HTML插件
        label=None,                  用于生成Label标签或显示内容
        initial=None,                初始值
        help_text='',                帮助信息(在标签旁边显示)
        error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
        show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
        validators=[],               自定义验证规则
        localize=False,              是否支持本地化
        disabled=False,              是否可以编辑
        label_suffix=None            Label内容后缀
     
     
    CharField(Field)
        max_length=None,             最大长度
        min_length=None,             最小长度
        strip=True                   是否移除用户输入空白
     
    IntegerField(Field)
        max_value=None,              最大值
        min_value=None,              最小值
     
    FloatField(IntegerField)
        ...
     
    DecimalField(IntegerField)
        max_value=None,              最大值
        min_value=None,              最小值
        max_digits=None,             总长度
        decimal_places=None,         小数位长度
     
    BaseTemporalField(Field)
        input_formats=None          时间格式化   
     
    DateField(BaseTemporalField)    格式:2015-09-01
    TimeField(BaseTemporalField)    格式:11:12
    DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
     
    DurationField(Field)            时间间隔:%d %H:%M:%S.%f
        ...
     
    RegexField(CharField)
        regex,                      自定制正则表达式
        max_length=None,            最大长度
        min_length=None,            最小长度
        error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
     
    EmailField(CharField)      
        ...
     
    FileField(Field)
        allow_empty_file=False     是否允许空文件
     
    ImageField(FileField)      
        ...
        注:需要PIL模块,pip3 install Pillow
        以上两个字典使用时,需要注意两点:
            - form表单中 enctype="multipart/form-data"
            - view函数中 obj = MyForm(request.POST, request.FILES)
     
    URLField(Field)
        ...
     
     
    BooleanField(Field)  
        ...
     
    NullBooleanField(BooleanField)
        ...
     
    ChoiceField(Field)
        ...
        choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
        required=True,             是否必填
        widget=None,               插件,默认select插件
        label=None,                Label内容
        initial=None,              初始值
        help_text='',              帮助提示
     
     
    ModelChoiceField(ChoiceField)
        ...                        django.forms.models.ModelChoiceField
        queryset,                  # 查询数据库中的数据
        empty_label="---------",   # 默认空显示内容
        to_field_name=None,        # HTML中value的值对应的字段
        limit_choices_to=None      # ModelForm中对queryset二次筛选
         
    ModelMultipleChoiceField(ModelChoiceField)
        ...                        django.forms.models.ModelMultipleChoiceField
     
     
         
    TypedChoiceField(ChoiceField)
        coerce = lambda val: val   对选中的值进行一次转换
        empty_value= ''            空值的默认值
     
    MultipleChoiceField(ChoiceField)
        ...
     
    TypedMultipleChoiceField(MultipleChoiceField)
        coerce = lambda val: val   对选中的每一个值进行一次转换
        empty_value= ''            空值的默认值
     
    ComboField(Field)
        fields=()                  使用多个验证,如下:即验证最大长度20,又验证邮箱格式
                                   fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
     
    MultiValueField(Field)
        PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
     
    SplitDateTimeField(MultiValueField)
        input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
        input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
     
    FilePathField(ChoiceField)     文件选项,目录下文件显示在页面中
        path,                      文件夹路径
        match=None,                正则匹配
        recursive=False,           递归下面的文件夹
        allow_files=True,          允许文件
        allow_folders=False,       允许文件夹
        required=True,
        widget=None,
        label=None,
        initial=None,
        help_text=''
     
    GenericIPAddressField
        protocol='both',           both,ipv4,ipv6支持的IP格式
        unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
     
    SlugField(CharField)           数字,字母,下划线,减号(连字符)
        ...
     
    UUIDField(CharField)           uuid类型
        ...
    View Code

    a. 字段分类: 

    1. 验证

    #required
    #error_messages
    class TestForm(Form):
        t1 = fields.CharField(
            required=True,
            max_length=8,
            min_length=2,
            error_messages={
                "required":"不能为空",
                "max_length":"太长",
                "min_length":"太短",
            }
        )
        t2 = fields.IntegerField(
            min_value=10,
            max_value=1000,
            error_messages={
                "required": "t2不能为空",
                "invalid":"t2格式错误,必须是数字",
                "min_value":"必须大于10",
                "max_value":"必须小于1000",
            }
        )
    
        t3 = fields.EmailField(
            error_messages={
                "required": "t3不能为空",
                "invalid": "t3格式错误,必须是邮箱格式",
            }
        )
        t4 = fields.URLField()
        t5 = fields.SlugField()
        t6 = fields.GenericIPAddressField()
        t7 = fields.DateField()
        t8 = fields.DateTimeField()
        t9 = fields.RegexField("139d+")
    View Code

    2. 生成html标签

    Field
        widget=None,                 HTML插件
        label=None,                  用于生成Label标签或显示内容
        initial=None,                初始值
        help_text='',                帮助信息(在标签旁边显示)
        show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
        disabled=False,              是否可以编辑
        label_suffix=None            Label内容后缀
    
    ############# views.py
    
    class TestForm(Form):
        t1 = fields.CharField(
            label="用户名",
            label_suffix=":",       #label内容后缀   前端写obj.as_p才显示
            help_text="....",       #提供帮助信息
            initial="666",
            required=True,
            max_length=8,
            min_length=2,
            error_messages={
                "required":"不能为空",
                "max_length":"太长",
                "min_length":"太短",
            }
        )
    
    
    def test(request):
        if request.method == "GET":
            obj = TestForm()
            return render(request,"test.html",{"obj":obj})
        else:
            obj = TestForm(request.POST)
            if obj.is_valid():
                print(obj.cleaned_data)
            else:
                print(obj.errors)
            return render(request, "test.html")
    
    
    
    #前端  html  两种方式显示
    
    #方式一:
    <form action="/test/" method="POST">
        {% csrf_token %}
        {{ obj.t1.label }}{{ obj.t1.label_suffix }}
        {{ obj.t1 }}{{ obj.t1.help_text }}
        <input type="submit" value="提交">
    </form>
    
    方式二:
    <form action="/test/" method="POST">
        {% csrf_token %}
        {{ obj.as_p }}
        <input type="submit" value="提交">
    </form>
    示例演示

    保留上次提交的内容:

    #obj = TestForm()
    #obj.t1  <input type="text" name=t1/>
    
    #obj = TestForm(request.POST)
    #obj.t2  <input type="text" name=t1 values="xxx" />
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <form action="/test/" method="POST" novalidate>
        {% csrf_token %}
        <p>
            {{ obj.t1 }}{{ obj.errors.t1.0 }}
        </p>
        <p>
            {{ obj.t2 }}{{ obj.errors.t2.0 }}
        </p>
        <input type="submit" value="提交">
    </form>
    
    
    
    
    </body>
    </html>
    test.html
    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from django.forms import Form,fields
    
    
    class TestForm(Form):
        t1 = fields.CharField(required=True,max_length=8,min_length=2,
            error_messages={
                "required":"不能为空",
                "max_length":"太长",
                "min_length":"太短",
            }
        )
    
        t2 = fields.EmailField()
    
    def test(request):
        if request.method == "GET":
            obj = TestForm()        #没有参数,相当于去创建 #input等标签,<input type="text" name="t2">,没有value
            return render(request,"test.html",{"obj":obj})
        else:
            obj = TestForm(request.POST)    #取到数据
            if obj.is_valid():
                print(obj.cleaned_data)
            else:
                print(obj.errors)
            return render(request, "test.html",{"obj":obj}) #<input type="text" name="t2" value="xx">
    View.py

    b. Form类参数验证:  

    #obj = xxForm({"title":"全栈一期"})		#默认第一个参数是data,要验证
    #obj = xxForm(data = {"title":"全栈一期"})	#参数data要验证,有错误前端会提示 obj.errors.title.0
    #obj = xxForm(request.POST)			#request.POST默认是data = request.POST
    
    #obj = xxForm(initial = {"title":"全栈一期"})	#initial  #不验证

    三. Form 插件 

    a. Select框:

    #单选
    cls_id = fields.IntegerField(
        # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
        widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'))
    )
     
    cls_id = fields.ChoiceField(
        choices=models.Classes.objects.values_list('id','title'),
        widget=widgets.Select(attrs={'class': 'form-control'})
    )
     
     
    obj = FooForm({'cls_id':1})
     
    #多选
    xx = fields.MultipleChoiceField(
        choices=models.Classes.objects.values_list('id','title'),
        widget=widgets.SelectMultiple
    )
     
    obj = FooForm({'cls_id':[1,2,3]}) 
    View Code

    1. 修复编辑老师时,不能实时更新班级列表 

    方式一(推荐): 

    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator
    
    class TeacherForm(Form):
        tname = fields.CharField(min_length=2)
        xx = fields.MultipleChoiceField(
            # choices=models.Classes.objects.values_list("id","title"),
            widget=widgets.SelectMultiple
        )
        def __init__(self,*args,**kwargs):
            super(TeacherForm,self).__init__(*args,**kwargs)
            self.fields["xx"].choices =models.Classes.objects.values_list("id","title")
    View Code

    方式二:

    from django import forms
    from django.forms import fields
    from django.forms import widgets
    from django.forms import models as form_model
    from django.core.exceptions import ValidationError
    from django.core.validators import RegexValidator
    
    
    class TeacherForm(Form):
        tname = fields.CharField(min_length=2)
        xx = form_model.ModelMultipleChoiceField(queryset=models.Classes.objects.all())
        # xx = form_model.ModelChoiceField(queryset=models.Classes.objects.all())
    
    
    class Classes(models.Model):
        title = models.CharField(max_length=32)
    
        def __str__(self):
            return self.title
    View Code

    b. checkbox:

    class TestForm(Form):
        t1 = fields.CharField(
            widget=widgets.Textarea(attrs={})
        )
    
        #单选框
        t2 = fields.CharField(
            widget=widgets.CheckboxInput
        )
    
        #复选框
        t3 = fields.MultipleChoiceField(
            choices=[(1,"篮球"),(2,"足球"),(3,"溜溜球")],
            widget=widgets.CheckboxSelectMultiple
        )
    
    
    def test(request):
        obj = TestForm(initial={"t3":[2,3]})
        return render(request,"test.html",{"obj":obj})
    View Code

    c. radio 

    class TestForm(Form):
       
        t4 = fields.MultipleChoiceField(
            choices=[(1,"篮球"),(2,"足球"),(3,"溜溜球")],
            widget=widgets.RadioSelect
        )
        t5 = fields.ChoiceField(
            choices=[(1,"篮球"),(2,"足球"),(3,"溜溜球")],
            widget=widgets.RadioSelect
        )
    
    
    
    def test(request):
        obj = TestForm()
        return render(request,"test.html",{"obj":obj})
    View Code

    四. 提交方式 

    1. 两种提交方式: 

    提交方式:
        - Form提交(刷新,失去上次内容)
        - Ajax提交(不刷新,保留上次内容) 

    a. form提交

    urlpatterns = [
    
        url(r'^login/', views.login),
    ]
    urls.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form method="POST" action="/login/">
            {% csrf_token %}
            <p>
                用户:<input type="text" name="username"/>{{ obj.errors.username.0 }}
            </p>
            <p>
                密码:<input type="password" name="password"/>{{ obj.errors.password.0 }}
            </p>
            <input type="submit" value="提交" />{{ msg }}
        </form>
    </body>
    </html>
    login.html
    from django.shortcuts import render,HttpResponse,redirect
    
    from django.forms import Form
    from django.forms import fields
    class LoginForm(Form):
        # 正则验证: 不能为空,6-18
        username = fields.CharField(
            max_length=18,
            min_length=6,
            required=True,
            error_messages={
                'required': '用户名不能为空',
                'min_length': '太短了',
                'max_length': '太长了',
            }
        )
        # 正则验证: 不能为空,16+
        password = fields.CharField(min_length=16,required=True)
        # email = fields.EmailField()
        # email = fields.GenericIPAddressField()
        # email = fields.IntegerField()
    
    
    def login(request):
        if request.method == "GET":
            return render(request,'login.html')
        else:
           obj = LoginForm(request.POST)
           if obj.is_valid():
               # 用户输入格式正确
               print(obj.cleaned_data) # 字典类型
               return redirect('http://www.baidu.com')
           else:
               # 用户输入格式错误
               return render(request,'login.html',{'obj':obj})
    
    Views.py
    Views.py

    b. Ajax提交

    urlpatterns = [
    
        url(r'^ajax_login', views.ajax_login),
    ]
    urls.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <h3>用户登录</h3>
        <form id="f1">
            {% csrf_token %}
            <p>
                <input type="text" name="user">{{ obj.errors.user.0 }}
            </p>
            <p>
                <input type="password" name="pwd">{{ obj.errors.pwd.0 }}
            </p>
    
    
            <a onclick="Ajax_sublit()">提交</a>
    
        </form>
    
        <script src="/static/jquery-3.2.1.js"></script>
        <script>
            function Ajax_sublit() {
                $(".c1").remove();
                $.ajax({
                    url:"/ajax_login/",
                    type:"POST",
                    data:$("#f1").serialize(),
                    dataType:"JSON",
                    success:function (arg) {
                        console.log(arg);
                        if(arg.staus){
    
                        }else {
                            $.each(arg.msg,function (index,value) {
                                console.log(index,value);
                                var tag = document.createElement("span");
    {#                            var tag = $("<span>");#}
                                tag.innerHTML = value[0];
    {#                            tag.HTML(value[0]);#}
                                tag.className = "c1";
                                $("#f1").find('input[name="'+ index +'"]').after(tag);
    
                            })
                        }
                    }
                })
            }
        </script>
    
    
    </body>
    </html>
    login.html
    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from django.forms import Form,fields
    
    
    class LoginForm(Form):
        user = fields.CharField(required=True)
        pwd = fields.CharField(min_length=6)
    
    
    
    def ajax_login(request):
        import json
        ret = {"status":True,"msg":None}
        if request.method == "GET":
            return render(request,"login.html")
        else:
            obj = LoginForm(request.POST)
            if obj.is_valid():
                print(obj.cleaned_data)
            else:
                ret["status"] = False
                ret["msg"] = obj.errors
    
            v = json.dumps(ret)
            return HttpResponse(v)
    View.py
    有一种能力,是持续不断的努力
  • 相关阅读:
    url中的jsessionid解释
    电脑双网卡配置
    jedis api使用
    RedisTemplate访问Redis数据结构
    动态jdk启动项目
    导入导出Excel工具类ExcelUtil
    git超详细教程
    Linux配置SSH免用户免密码登陆
    hdfs shell的基本操作以及hdfsWeb查看文件
    清除redis的特定前缀的key
  • 原文地址:https://www.cnblogs.com/shaojiafeng/p/7994706.html
Copyright © 2011-2022 走看看