django之form组件

form组件(功能)html

  1. 生成html标签前端

    前端页面是form类的对象生成的--->生成HTML标签功能git

    当用户名和密码输入为空或输错以后,页面都会提示--->用户提交校验功能正则表达式

    当用户输错以后,再次输入 上次的内容还保留在input框--->保留上次输入内容数据库

 

​ 1.1 Form经常使用字段和插件---字段用于对用户请求数据的验证,插件用于自动生成HTMLdjango

initial  初始值,input框里面的初始值
class LoginForm(forms.Form):
username = forms.CharField(
    min_length = 8,
    label = '用户名',
    initial = '张三')
error_messages重写错误信息
class LoginForm(formS.Form):
username = forms.CharField(
min_length = 8,
label = '用户名:',
initial = '张三',
error_messages={
'required':'不能为空',
'invalid':'格式错误',
'min_length':'用户名最短8位'
})

Passwordsession

class LoginForm(forms.Form):
password = forms.CharField(
min_length = 6,
label = '密码',
widget = forms.widgets.PasswordInput(
attrs={'class':'c1'},render_value = True))
这个密码字段和其余字段不同,默认在前端输入数据错误的时候,点击提交以后,默认不保存原来数据的,可是能够经过这个render_value = True让这个字段在前端保留用户输入的数据
radioSelect--->单radio值为字符串
class LoginForm(forms.Form):
username = forms.CharField(
min_length = 8,
label = '用户名',
initial = '张三',
error_messages = {
'required':'不能为空',
'invalid':'格式错误',
'min_length':'用户名最短8位'
}
password = forms.CharField(label='密码',min_length=6)
gender = forms.fields.ChoiceField(
choices = ((1,'男'),(2,'女'),)
label='性别',
initial = 2,
widget = forms.widgets.RadioSelect())
单选Select
class LoginForm(forms.Form):
hobby = forms.fields.ChoiceField(###单选框用的是ChoiceField,而且插件用的是Select,否则验证会报错,Select a Valid choice的错误
choice = ((1,'抽烟'),(2,'喝酒'),(3,'烫头')),
label = '爱好',
initial = 3,
widget = forms.widgets.Select())
多选Select
class LoginForm(forms.Form):
hobby = forms.fields.MultipleChoiceField(---多选框用的是MultipleChoiceFiled,而且插件用的是SelectMultiple,否则验证会报错
choices = ((1,'篮球'),(2,'足球'),(3,'羽毛球'),),
initial = 3,
widget = forms.widgets.SelectMultiple()
)
单选checkbox
calss LoginForm(forms.Form):
keep = forms.fields.ChoiceField(
label = '是否记住密码',
initial = 'checked',
widget = forms.widget.CheckboxInput()
)

示例:函数

单选checkbox:
class TestForm(forms.Form):
keep = forms.Fields.ChoiceField(
choices = (('True',1),('False',2),),
label = '是否七天内自动登陆',
initial = '1',
widget = forms.widgets.CheakboxInput(),)

选中:'True'   #form只是帮咱们作校验,校验选择内容的时候,就是看在没在咱们的choices里面,里面有这个值,表示合法,没有就不合法
    没选中:'False'
    ---保存到数据库里面  keep:'True'
    if keep == 'True':
        session 设置有效期7天
    else:
        pass
多选checkbox
class LoginForm(forms.Form):
hobby = forms.Fields.MultipleChoiceField(
choices = ((1,'篮球'),(2,'足球'),(3,'羽毛球'),),
label = '爱好',
initial = 2,
widget = forms.widgets.ChectboxSelectMultiple())
date类型
from django import forms
class BookForm(forms.Form):
date = forms.DateField(widget=widgets.TextInput(attrs={'type':'date'}))

choice字段注意事项:ui

​ 在使用选择标签时,须要注意choices的选项能够配置从数据库中获取,可是因为是静态字段 获取的值没法实时更新,须要重写构造方法从而实现choice实时更新。插件

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

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类型
内置字段
  1. 保留原来的数据
 
  1. 校验用户提交的数据
RegexValidator验证器
from django import forms
class MyForm(forms.Form):
user = forms.CharField(
validators = [RegexValidator(r'^[0-9]+$','请输入数字'),
RegexValidator(r'^159[0-9]+$','数字必须以159开头')],)

自定义验证器

import re
from django import forms
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 PublishForm(forms.Form):
title = fields.CharField(max_length=20,
min_length=5,
error_message{
'required':'标题不能为空',
'min_length':'标题最少为5个字符',
'max_length':'标题最多为20个字符'
},
widget = forms.widgets.TextInput(attrs={'class':'form-control','placeholder':'标题5-20个字符'}))
#使用自定义验证规则
phone = fields.CharField(validators=[mobile_validate,],
error_messages={
'required':'手机不能为空'
},
widget = forms.widgets.TextInput(attrs={'class':'form-control','placeholder':u'手机号码'})),
email = fields.EmailField(required=False,error_message={
'required':u'邮箱不能为空','invalid':u'邮箱格式错误'
},
widget = forms.widgets.TextInput(attrs={'class':'form-control','placeholder':u'邮箱'}))
  1. Hook钩子方法

  2. 1 局部钩子(在Form类中定义clean_字段名()方法,就能实现对特定字段进行校验)

from django import forms
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

4.2 全局钩子

咱们在Form类中定义clean()方法,就可以实现对字段进行全局校验,字段所有验证完,局部钩子也所有执行完以后,执行这个全局钩子校验
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(self):
        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 #全局钩子要返回全部的数据
        else:
            self.add_error('re_password', '两次密码不一致') #在re_password这个字段的错误列表中加上一个错误,而且clean_data里面会自动清除这个re_password的值,因此打印clean_data的时候会看不到它
            raise ValidationError('两次密码不一致')
相关文章
相关标签/搜索