zoukankan      html  css  js  c++  java
  • Django-Form组件-forms.Form

    forms.Form

    ​ 在之前的示例HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。

    与此同时很多时候都需要对用户的输入做校验,比如校验用户是否输入,输入的长度和格式等是否符合条件。如果用户输入的内容有错误就需要在页面上相应的位置显示对应的错误信息。

    Django form组件就实现了上面所述的功能。

    总 结一下,其实form组件的主要功能如下:

    • 生成页面可用的HTML标签
    • 对用户提交的数据进行校验
    • 保留上次输入内容

    常用字段

    .CharField() 输入框

    属性 描述 属性 描述
    label 设置label标签 initial 设置默认值
    min_length 最小长度 widget 输入框属性
    (forms.PasswordInput
    表示密码输入框)
    error_messages 重写错误类型
    使用字典可以重写
    required True表示必填;Flase表示可以为空
    validators 自定义校验器函数列表 max_length 超过做大限度之后,不能继续输入

    .ChoiceField() 单选框

    属性 描述 属性 描述
    label choices 设置选项((),(),())
    initial 设置默认值[] error_messages 重定义错误提示
    required 是否必填 widget 选择框类型

    .MultipleChoiceField() 多选框

    属性 描述 属性 描述
    label choices 设置选项((),(),())
    initial 设置默认值[] error_messages 重定义错误提示
    required 是否必填 widget 选择框类型

    .ModelChoiceField()和.ModelMultipleChoiceField()

    在.ChoiceField()和.MultipleChoiceField()的升级款,不需要重启项目,就能够从数据库实时将数据的数据提取出来。

    特殊属性:queryset,查询的是数据库的数据

    【所有字段属性】

    所有字段
    	'Field', 'CharField', 'IntegerField',
        'DateField', 'TimeField', 'DateTimeField', 'DurationField',
        'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
        'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
        'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
        'SplitDateTimeField', 'GenericIPAddressField', 'FilePathField',
        'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField', 'UUIDField',
        
    # 对应属性
    Field
        required=True,               是否允许为空
        widget=None,                 HTML插件
        label=None,                  用于生成Label标签或显示内容
        initial=None,                初始值
        help_text='',                帮助信息(在标签旁边显示)
        error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
        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类型
    

    使用流程

    视图中

    第一步:引入forms插件from django import forms

    第二步:创建表单类

    第三步:创建视图函数,实例化表单对象,传给模板

    from django import forms
    # 创建表单类
    class Formtable(forms.Form):
        user = forms.CharField(
            label='用户名',
            min_length=6,
            required=True,
            error_messages={
                'required':'该字段不得为空',
                'min_length':'用户名至少六位'
            }
    
        )
    
        pwd = forms.CharField(
            label='密码',
            widget=forms.PasswordInput,
            required=True,
            min_length=8,
            max_length=12,
            error_messages={
                'required': '该字段不得为空',
                'min_length':'密码长度不能少于8位',
                'max_length':'密码长度不能大于12位',
            }
        )
    
        gender = forms.ChoiceField(
            label='性别',
            choices=((1,'男'),(2,'女')),
            initial=[1,],
            widget=forms.RadioSelect,
        )
    
        hobby = forms.MultipleChoiceField(
            label='兴趣爱好',
            choices=choices=models.Hobby.objects.values_list('id','type'), //从数据库中提取数据
            initial= [1,2],
            widget=forms.CheckboxSelectMultiple,
        )
        S
        hobby = forms.ModelMultipleChoiceField(
            label='兴趣爱好',
            queryset=models.Hobby.objects.all(),
            initial=[1, ],
            widget=forms.CheckboxSelectMultiple,
        )
    
    def form_table2(request):
        form_obj = Formtable()
        if request.method == "POST":
            form_obj=Formtable(data=request.POST)  # data作用是提取POST中的值
            if form_obj.is_valid() :   # .is_valid判断数据是否可用,做校验,里边包含错误信息
                # 判断成功,插入到数据库
                return HttpResponse("数据已保存")
        return render(request, 'formtable2.html', {'form_obj':form_obj})
    
    
    注意: hobby虽然是能够从数据库中提取信息,但有一个问题是,当对数据库中的数据进行修改后,只有重新启动项目,才能够显示最新数据,要解决这个问题,需要使用.ModelMultipleChoiceField()
    
    hobby = forms.ModelMultipleChoiceField(
            label='兴趣爱好',
            queryset=models.Hobby.objects.all(),
            initial=[1, ],
            widget=forms.CheckboxSelectMultiple,
        )
        
    # 视图函数
    def formtable(request):
        form_obj = Formtable()
        if request.method == 'POST':
            form_obj = Formtable(request.POST)
            if form_obj.is_valid():
                print(form_obj.cleaned_data)  # 看看有哪些信息
                user = form_obj.cleaned_data.get('name')
                pwd = form_obj.cleaned_data.get('pwd')
                # 往数据库写数据
                return HttpResponse('注册成功')
            else:
                all_error = form_obj.errors.get("__all__")
                return render(request, 'Formtable.html', locals())
        return render(request,'zhuce.html',{'form_obj':form_obj})
    

    HTML中

    第一步:创建form标签

    第二步:接收form对象

    【常用属性】

    {{ form_obj.as_p }}    # 展示所有的字段
    
    {{ form_obj.user }}   # input框
    {{ form_obj.user.label }}   # label标签的中文提示
    {{ form_obj.user.id_for_label }}  # input框的id
    {{ form_obj.user.errors  }}    # 一个字段的错误信息
    {{ form_obj.user.errors.0  }}   # 一个字段的第一个错误信息
    {{ form_obj.errors  }}   # 所有字段的错误
    

    【示例】

    # 方式一:自动生成
    <form action="" method="post">
        {% csrf_token %}
        {{ form_obj.as_p }}   
        // as_p的意思是每一个字段占一个p标签,还有as_table,as_errord等等
        <button>注册</button>
    </form>
    
    # 方式二:单个生成
    <form action="" method="post" novalidate>
        {% csrf_token %}
        <p>
            <label for="{{ form_obj.user.id_for_label }}">{{ form_obj.user.label }}:</label>
            {{ form_obj.user}}  
            <span>{{ form_obj.user.errors.0 }}</span>
        </p>
        <p>
            <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}:</label>
            {{ form_obj.pwd}}  
            <span>{{ form_obj.pwd.errors.0 }}</span>
        </p>
        <p>
            <label> {{ form_obj.gender.label }}:</label>
            {{ form_obj.gender.0}} {{ form_obj.gender.1}}
        </p>
        <p>
            <label>{{ form_obj.hobby.label }}:</label>
            {% for i in  form_obj.hobby  %}
                {{ i }}
            {% endfor %}
        </p>
        <button>注册</button>
    </form>
    

    校验

    方式一:自定义校验函数

    # 第一步:导入ValidationError模块
    from django.core.exceptions import ValidationError
    
    # 第二步:自定义校验函数和校验规则,没有通过校验,抛出ValidationError异常
    def checkuser(value):
        if 'guest' in value:
            raise ValidationError("不能使用guest用户名")
    
    # 第三步:添加到要检验的Form字段中的validators属性
    class Formtable(forms.Form):
        user = forms.CharField(
            label='用户名',
            min_length=5,
            required=True,
            error_messages={
                'required':'该字段不得为空',
                'min_length':'用户名至少五位'
            },
            validators=[checkuser]
        )
    

    方式二:使用内置的validators

    # 第一步,导入相应的校验器,举例使用的是正则校验器,格式是('正则表达式','错误信息')
    from django.core.validators import RegexValidator
    
    # 第二步:在要检验的Form字段中的validators属性,直接添加校验器和校验规则
    pwd = forms.CharField(
            label='密码',
            widget=forms.PasswordInput,
            required=True,
            min_length=8,
            max_length=12,
            error_messages={
                'required': '该字段不得为空',
                'min_length':'密码长度不能少于8位',
                'max_length':'密码长度不能大于12位',
            },
            validators=[RegexValidator(r"^[A-Z]",'请以大写字母开头')]
        )
    

    校验流程

    第一步:is_valid()中要执行full_clean():

    1. self._errors ={} 定义一个存放错误信息的字典
    2. self.cleaned_data = {} 定义一个存放有效数据的字典

    第二步:执行self._clean_fields()

    1. 先执行内置的校验和校验器的校验
    2. 有局部钩子,执行局部钩子

    第三步:执行 self.clean() 全局钩子

    局部钩子

    根据_clean_fields()中定义的那样 if hasattr(self, 'clean_%s' % name):,局部钩子的格式就是以clean_开头,定义局部钩子就是使用clean_字段名,获取字段的值使用的是self.clean_data.get('字段名')

    class Formtable(forms.Form):
    # 定义字段
        user = forms.CharField(
            label='用户名',
            min_length=5,
            required=True,
            error_messages={
                'required':'该字段不得为空',
                'min_length':'用户名至少五位'
            },
        )
        
        # 定义该字段的局部钩子
        def clean_user(self):
            # 局部钩子
            # 不通过校验,抛出异常,将异常信息以 {'name':value} 写入errors字典中
            # 通过校验,返回当前字段的值,把name返回到clean_data,将name写入clean_data字典中
            username = self.cleaned_data.get('user')
            print(username,type(username))
            if username == 'guest':
                raise ValidationError("不能使用guest用户名")
            return username
    

    全局钩子

    可以对多个字段进行额外的校验,比如注册时使用的确认密码,需要与第一次的密码进行匹配,这是就要用到全局钩子。

    # 定义Form组件
    class Formtable(forms.Form):
        name = forms.CharField(label='用户名',
                               error_messages={'required': '该字段是必填的~',},
                               validators=[usercheck,])
    
        pwd = forms.CharField(label='密码',
                              widget=forms.PasswordInput,
                              min_length=8,
                              error_messages={'required': '该字段是必填的~','min_length': '至少是8位'},
                              validators=[pwdcheck,])
    
        re_pwd = forms.CharField(label='确认密码',
                                 widget=forms.PasswordInput,
                                 min_length=8,
                                 error_messages={'required': '该字段是必填的~','min_length': '至少是8位'}
                                )
                                
    # 定义全局钩子
    	# 重写clean方法
    	# 校验失败,抛异常,将异常信息以{'__all__':[value,]} 写入 errors 字典中
    	# 校验成功,返回clean_data字典
    	# 抛出异常的类型为ValidationError
    	
        def clean(self):
        	# 程序能走到该函数,前面校验已经通过了,所以可以从cleaned_data中取出密码和确认密码 
            pwd = self.cleaned_data.get('pwd')
            repwd = self.cleaned_data.get('re_pwd')
            # 进行两次密码校验
            if pwd == repwd:
            	# 通过,直接返回cleaned_data
                return self.cleaned_data
            else:
            	# 失败,抛异常(ValidationError)
                self.add_error('re_pwd','两次密码不一致')
                raise ValidationError('两次密码不一致')
                
    # 全局钩子的错误提示不属于任何字段,而是在保存在__all__中,显示可以有两种方式:
    方式一:可以把它添加到一个字段中,然后显示出来,例如上代码else所示,以通过该字段显示错误信息
    方式二:在前端使用{{ myforms.errors.__all__.0 }}
    
    
  • 相关阅读:
    python之《set》
    python之 《zip,lambda, map》
    python之 socketserver模块的使用
    iOS FMDB小试了一下
    人生要自强不息-路遇瞎子感悟
    iOS Node Conflict svn冲突
    iOS 隐藏Status Bar
    iOS NSURLSession 封装下载类
    iOS NSFileManager
    iOS prototype Cells
  • 原文地址:https://www.cnblogs.com/jjzz1234/p/11629857.html
Copyright © 2011-2022 走看看