form组件

form组件

一、概述

我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。与此同时我们在好多场景下都需要对用户的输入做效验,比如效验用户是否输入,输入的长度和格式等正不正确。如果用户输入的内容有错误就需要在页面上相应的位置显示对应的错误信息。

Django form组件就实现上面所述的功能,form组件的主要功能如下:

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

二、form内置字段

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

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

方式一:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from app01 import models
class RecruitForm(forms.Form): price = fields.IntegerField() user_id = fields.IntegerField( widget=widgets.Select(choices=models.UserInfo.objects.values_list('id','username')) ) #动态绑定数据,数据源的实时更新 
def __init__(self,*args,**kwargs):
  super(RecruitForm,self).
__init__(*args,**kwargs)
  self.fields[
'user_id'].widget.choices=models.UserInfo.objects.values_list('id','username')

方法二:利用django提供的ModelChoiceField和ModelMultipleChoiceField字段来实现

from django import forms
from django.forms import fields
from django.forms import widgets
from app01 import models
from django.forms.models import ModelChoiceField
class RecruitForm(forms.Form):
    price = fields.IntegerField()
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=models.UserInfo.objects.values_list('id','username'))
    )
    #数据源的实时更新,不过要依赖于models中的str方法
    user_id2= ModelChoiceField(
        queryset=models.UserInfo.objects.all(),
        to_field_name='id'

    )

三、实例

1.radio Select

from django import forms
from django.forms import fields

class LoginForm(forms.Form):
    username = fields.CharField(
        min_length=8,
        label="用户名",
        initial="张三",
        error_messages={
            "required": "不能为空",
            "invalid": "格式错误",
            "min_length": "用户名最短8位"
        }
    )
    pwd = forms.CharField(min_length=6, label="密码")
    gender = forms.fields.ChoiceField(
        choices=((1, ""), (2, ""), (3, "保密")),
        label="性别",
        initial=3,
        widget=forms.widgets.RadioSelect()
    )

2.单选Select

from django import forms
from django.forms import fields
class LoginForm(forms.Form):
    hobby =fields.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=3,
        widget=forms.widgets.Select()
    )

3.多选Select

from django import forms
from django.forms import fields
class LoginForm(forms.Form):
    hobby = fields.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.SelectMultiple()
    )

4.具体验证

(1)views.py

from django.shortcuts import render,HttpResponse,redirect

from django import forms
from django.forms import fields
# Create your views here.
class F1Form(forms.Form):
    user = fields.CharField(
            max_length=18,
            min_length=6,
            required=True,
            error_messages={
                'required':'用户名不能为空',
                'max_length':'长度太长了',
                'min_length':'长度至少6位',
            }
    )
    pwd = fields.CharField(
            min_length=6,
            required=True,
            error_messages={
                'required':'密码不能为空',
                'min_length':'长度至少6位',
            }
    )
    age = fields.IntegerField(
            required=True,
            error_messages={
                'required':'年龄不能为空',
                'invalid':'格式错误,必须为数字'
            }
    )
    email = fields.EmailField(
            required=True,
            error_messages={
                'required':'邮箱不能为空',
                'invalid':'格式错误,必须是邮箱格式',
            }
    )

def f1(request):
    if request.method == 'GET':
        obj = F1Form()
        return render(request,'f1.html',{'obj':obj})
    else:
        # u = request.POST.get('user')  #不能为空,长度6-18
        # p = request.POST.get('pwd')  #不能为空,长度32
        # a = request.POST.get('age')  #不能为空,数字类型
        # e = request.POST.get('email')  #不能为空,邮箱格式
        #1.检查是否为空
        #2.检查格式是否正确

        obj = F1Form(request.POST)
        #是否全部验证成功
        if obj.is_valid():
            #用户提交的数据
            print('验证成功',obj.cleaned_data)
            return redirect('http://www.baidu.com')
        else:
            print('验证失败',obj.errors)
            return render(request,'f1.html',{'obj':obj})

(2)f1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form id='fm' action="/f1/" method="post">
        <p>{{ obj.user }}{{ obj.errors.user.0 }}</p>
        <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
        <p>{{ obj.age }}{{ obj.errors.age.0 }}</p>
        <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <input type="submit" value="提交">

    </form>


</body>
</html>

四、验证扩展

1.RegexValidator模块

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator
 
class MyForm(Form):
    user = fields.CharField(
        validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^139[0-9]+$', '数字必须以139开头')],
    )

2. RegexField字段

from django.forms import Form
from django.forms import widgets
from django.forms import fields
 
 
class MyForm(Form):
    user = fields.RegexField(r'^[0-9]+$',error_messages={'invalid':'.....'})

3.自定义方法

from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
class AjaxForm(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=models.UserInfo.objects.values_list('id','username'))
    )
    #自定义方法 clean_字段名
    #必须返回值 self.cleaned_data['字段名']
    #出错:raise ValidationError('用户名已存在')
    # def clean_username(self):
    #     v = self.cleaned_data['username']
    #     if models.UserInfo.objects.filter(username=v).count():
    #         raise ValidationError('用户名已存在')
    #
    #
    #     return v
    def clean_user_id(self):
        return self.cleaned_data['user_id']

    def clean(self):  #整体的错误信息
        value_dict = self.cleaned_data
        v1 = value_dict.get('username')
        v2 = value_dict.get('user_id')
        if v1 == 'root'and v2 == 1:
            raise ValidationError('整体错误')
        return self.cleaned_data

def ajax(request):
    if request.method == "GET":
        obj = AjaxForm()
        return render(request,'ajax.html',{'obj':obj})
    else:
        ret = {'status':True,'message':None}
        import json
        obj = AjaxForm(request.POST)
        if obj.is_valid():
            # print(obj.cleaned_data)
            return HttpResponse(json.dumps(ret))

        else:
            ret['status']=False
            ret['message']=obj.errors
            print(obj.errors)
            return HttpResponse(json.dumps(ret))
posted @ 2019-11-17 22:26  流浪代码  阅读(152)  评论(0编辑  收藏  举报