Form组件

一  概述

form组件的实质就是生成自带验证功能的input标签

form组件的主要功能如下:

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

form表单的输出不包含submit 按钮,和表单的

 标签

二  Form组件样式

<form action="/login/" method="post" novalidate>     {#novalidate不需要验证#}
    {% csrf_token %}
   {{ form_obj.as_p }}           {# 将user、pwd等所有标签渲染在<p>标签中,包含input、label、helptext标签#}
    <table>                         {# 自己提供table#}
        {{ form_obj.as_table }}    {# 将user、pwd等所有标签渲染在<tr>标签中,包含input、label、helptext标签#}
    table>
  <ul>                              {# 自己提供ul#}
        {{ form_obj.as_ul }}      {# 将user、pwd等所有标签渲染在<li>标签中,包含input、label、helptext标签#}
   ul>

   {{ form_obj.user }}           {# 渲染user标签,只包含input标签#}
   {{ form_obj.user.label}}      {# 渲染user.label标签,包含label标签,字符串形式#}
   {{ form_obj.user.help_text}}   {# 渲染user.helptext标签,包含helptext标签,字符串形式#}
  {{form_obj.user.id_for_label}}  {#input的id #}   {{ form_obj.errors }}   {# 包含所有错误,ul的形式#} {{ form_obj.errors.user }}   {# 包含user标签中的所有错误,ul的形式#} {{ form_obj.errors.user.0 }}   {# user标签中的第一个错误,字符串的形式#}
<p><input type="submit" value="提交">p> form>

因为{{ form_obj.user }}只包含input,不包含label和helptext,因此常用for循环

<form action="/login/" method="post" novalidate>
   {% csrf_token %}
    {% for field in form_obj %}
        <div>
        {{ field.label }}
        {{ field }}
        div>
    {% endfor %}

实例:

Html

<form action="/login/" method="post" novalidate>     #novalidate不对输入进行验证的表单
    {% csrf_token %}
    {{ form_obj.as_p }}
    <p><input type="submit" value="提交">p>
form>

myform.py 

from django import forms
from django.forms import widgets
class LoginForm(forms.Form):
    user = forms.CharField(max_length=12, min_length=5,
                           label="用户名",
                           help_text="6~16个字符,区分大小写",
                           error_messages={"required": "不能为空",
                                           "min_length": "最小长度为5"})
    pwd = forms.CharField(
        help_text="6~16个字符,区分大小写",
        error_messages={
            "invalid": "格式错误"},
        widget=widgets.PasswordInput(attrs={"class": "active"}))  #password插件

 views

def login(request):
    form_obj = myforms.Loginform()
    if request.method == "POST":
        form_obj = myforms.Loginform(request.POST)
        if form_obj.is_valid():
            return HttpResponse('ok')
    # get方式或者验证不通过返回
    return render(request, 'login.html', {'form_obj': form_obj})

三  内置字段

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

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类型

四  插件

1. 常用插件

from django import forms
from django.forms import widgets
class LoginForm(forms.Form): # 单radio,显示为ul形式,返回值为字符串 user1 = forms.fields.CharField( label='city', initial=2, widget=widgets.RadioSelect(choices=((1, '上海'), (2, '北京'),))) # 单radio,显示为ul形式,返回值为字符串 user2 = forms.fields.ChoiceField( label='city', choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.RadioSelect) # 单select,显示为下拉框,返回值为字符串 user3 = forms.fields.CharField( initial=2, widget=widgets.Select(choices=((1, '上海'), (2, '北京'),))) # 单select,显示为下拉框,返回值为字符串 user4 = forms.fields.ChoiceField( choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.Select) # 多选select,显示为下拉框,返回值为列表 user5 = forms.fields.MultipleChoiceField( choices=((1, '上海'), (2, '北京'),), initial=[1,2], widget=widgets.SelectMultiple) # 单checkbox,不能有选项,只有被选和未选中 user6 = forms.fields.CharField( label="是否记住密码", initial="checked", widget=widgets.CheckboxInput()) # 多选checkbox,返回值为列表 user7 = forms.fields.MultipleChoiceField( initial=[2, ], choices=((1, '上海'), (2, '北京'),), widget=widgets.CheckboxSelectMultiple)

2. choice字段实时更新

在使用选择标签时,需要注意choices的选项可以配置从数据库中获取,但是由于是静态字段 获取的值无法实时更新,需要重写构造方法从而实现choice实时更新。

2.1 方式一

初始化函数调用数据库内容

from django.forms import Form
from django.forms import widgets
from django.forms import fields
class MyForm(Form):
    user = fields.ChoiceField(
        # choices=((1, '上海'), (2, '北京'),),
        initial=2,
        widget=widgets.Select
    )
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['user'].choices = models.Classes.objects.all().values_list('id', 'caption')

self.fields为:

OrderedDict([('user', )])

2.2 方式二

使用django提供的ModelChoiceField和ModelMultipleChoiceField字段来实现

from django import forms
from django.forms import fields
from django.forms import models as form_model

class FInfo(forms.Form):
    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  # 多选
    # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())  # 单选

3. 内置插件

  TextInput(Input)
   NumberInput(TextInput)
   EmailInput(TextInput)
   URLInput(TextInput)
   PasswordInput(TextInput)
   HiddenInput(TextInput)
   Textarea(Widget)
   DateInput(DateTimeBaseInput)
   DateTimeInput(DateTimeBaseInput)
   TimeInput(DateTimeBaseInput)
   CheckboxInput
   Select
   NullBooleanSelect
   SelectMultiple
   RadioSelect
   CheckboxSelectMultiple
   FileInput
   ClearableFileInput
   MultipleHiddenInput
   SplitDateTimeWidget
   SplitHiddenDateTimeWidget
   SelectDateWidget

五  自定义校验

#正常校验
from django import forms
from django.forms import widgets
class LoginForm(forms.Form):
    user = forms.CharField(max_length=12, min_length=5,
                           label="用户名",
                           help_text="6~16个字符,区分大小写",
                           error_messages={"required": "不能为空",
                                           "min_length": "最小长度为5"})

1. RegexValidator验证器

validators = [ 校验器1,校验器2 ]

from django.forms import Form
from django.forms import fields
from django.core.validators import RegexValidator

class MyForm(Form):
    user = fields.CharField(
        # validators为关键字
        validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],)

2. 自定义方法抛异常

from django import forms
from django.forms import fields
from django.core.exceptions import ValidationError

def usercheck(value):
    if "matt" in value:
        raise ValidationError('matt是恐怖分子')

class MyForm(forms.Form):
    user = fields.CharField(max_length=5, validators=[usercheck])

3. 自定义类抛异常

import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError

# 自定义验证规则
def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')

class MyForm(Form):
    title = fields.CharField(max_length=20,min_length=5,
                             error_messages={'required': '标题不能为空',
                                             'min_length': '标题最少为5个字符',
                                             'max_length': '标题最多为20个字符'},
                             widget=widgets.TextInput(attrs={'class': "form-control",
                                                             'placeholder': '标题5-20个字符'}))
    # 使用自定义验证规则
    phone = fields.CharField(validators=[mobile_validate, ],
                             error_messages={'required': '手机不能为空'},
                             widget=widgets.TextInput(attrs={'class': "form-control",
                                                             'placeholder': u'手机号码'}))

    email = fields.EmailField(error_messages={'required': u'邮箱不能为空', 'invalid': u'邮箱格式错误'},
                              widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))

4. 钩子

钩子的作用就是创建两层验证机制,第一层为Django自带验证,第二层为自定义验证。钩子可以成为多重验证机制

4.1 局部钩子

局部、全局的区分指的是clearn_data内部数据是局部还是全局的

源码解析

 

def _clean_fields(self):
    for name, field in self.fields.items():
        if field.disabled:
            value = self.get_initial_for_field(field, name)
        else:
            value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
        try:
            if isinstance(field, FileField):
                initial = self.get_initial_for_field(field, name)
                value = field.clean(value, initial)
            else:
                value = field.clean(value)
            self.cleaned_data[name] = value       #第一层Django自带验证通过后加入clearn_data中
            if hasattr(self, 'clean_%s' % name):
                value = getattr(self, 'clean_%s' % name)()
                self.cleaned_data[name] = value     #第二层自定义验证后再重新加入clearn_data中         
        except ValidationError as e:
            self.add_error(name, e)

实例:

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="张三",
        error_messages={
            "required": "不能为空",
            "invalid": "格式错误",
            "min_length": "用户名最短8位"},
        widget=forms.widgets.TextInput(attrs={"class": "form-control"}))
    ...
    # 定义局部钩子,用来校验username字段,自动通过反射调用
    def clean_username(self):
        value = self.cleaned_data.get("username")
        if "666" in value:
            raise ValidationError("光喊666是不行的")
        else:
            return value   #防止版本问题,必须返回value值

4.2 全局钩子

全局钩子是每一个字段完成Django自带和自定义验证后,再进行一次验证,可以理解为第三次验证

源码解析

self._clean_fields()    #自带与自定义,验证每一个字段
self._clean_form()      #完成每一个字段验证后再进行全局验证
self._post_clean()

def _clean_form(self):
    try:
        cleaned_data = self.clean()  #此处的cleaned_data包含所有字段,self.clean()为自定义全局钩子
    except ValidationError as e:
        self.add_error(None, e)
    else:
        if cleaned_data is not None:
            self.cleaned_data = cleaned_data

实例:

class LoginForm(forms.Form):
    ...
    password = forms.CharField(
        min_length=6,
        label="密码",
        widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}, render_value=True))
    re_password = forms.CharField(
        min_length=6,
        label="确认密码",
        widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}, render_value=True))
# 局部钩子实现全局功能,一定注意自带验证的先后顺序,即cleaned_data内部的数据 def clean_re_password(self):    #名称与全局钩子不一致 password_value = self.cleaned_data.get('password') re_password_value = self.cleaned_data.get('re_password') #clean_data中的数据为经过验证的字段,没有未经过验证的字段 if password_value == re_password_value: return re_password_value else: raise ValidationError('两次密码不一致')
# 定义全局的钩子,用来校验密码和确认密码字段是否相同 def clean(self):        #clean()名称不能错,与源码对应 password_value = self.cleaned_data.get('password') re_password_value = self.cleaned_data.get('re_password') if password_value == re_password_value: return self.cleaned_data #返回值为clean_data else: self.add_error('re_password', '两次密码不一致')  #添加错误,方便调用 raise ValidationError('两次密码不一致')    #在error._all_中,不方便使用

六  Bootstrap中Form验证

 

你可能感兴趣的:(Form组件)