35 django之Forms组件
一、form组件前戏
页面上获取用户输入的用户名和密码 然后判断用户名和密码是否符合一些条件 如果不符合则返回相应的提示信息 """ 自定义数据校验功能 主要步骤 1.搭建前端页面 标签渲染 2.校验数据是否合法 数据校验 3.返回相应的提示信息 提示信息 # 上述的三个步骤form组件都可以自动实现
views.py
def ab_form(request): error_dict={'user_msg':'',"pwd_msg":""} if request.method=='POST': username=request.POST.get("username") password=request.POST.get("password") if username=="jason": error_dict["user_msg"]="用户名格式不对" if len(password)==0: error_dict["pwd_msg"]="密码不能为空" return render(request,"ab_form.html",locals())
ab_form.html
二、form组件
1.基本定义/使用
views.py
# 与模型层类的定义相似 class MyForm(forms.Form): # username字段最短三位最长八位 username = forms.CharField(min_length=3, max_length=8) # password字段最短三位最长八位 password = forms.CharField(min_length=3, max_length=8) # email字段必须符合邮箱格式 email = forms.EmailField()
2.form组件数据校验功能
1.测试环境的准备 可以自己拷贝代码准备 2.其实在pycharm里面已经帮你准备一个测试环境 python console """ from app01 import views # 1 将带校验的数据组织成字典的形式传入即可 form_obj = views.MyForm({'username':'jason','password':'123','email':'123'})
# 2 判断数据是否合法 注意该方法只有在所有的数据全部合法的情况下才会返回True form_obj.is_valid() False
# 3 查看所有校验通过的数据 form_obj.cleaned_data {'username': 'jason', 'password': '123'}
# 4 查看所有不符合校验规则以及不符合的原因 form_obj.errors { 'email': ['Enter a valid email address.'] }
# 5 校验数据只校验类中出现的字段 多传不影响 多传的字段直接忽略 form_obj = views.MyForm({'username':'jason','password':'123','email':'123@qq.com','hobby':'study'}) form_obj.is_valid() True
# 6 校验数据 默认情况下 类里面所有的字段都必须传值 form_obj = views.MyForm({'username':'jason','password':'123'}) form_obj.is_valid() False """
1.在传递数据的时候 如果多传了额外字段 没有关系 form不校验
2.form组件内部定义的字段数据 默认都是必填的
可以通过修改参数required=False来控制是否必填
"""
3.form组件渲染标签
"""
1. 自动渲染的标签文本名称默认采用字段名首字母大写的形式,可以通过label参数自定义名称,如
username = forms.CharField(min_length=3,max_length=8,label='用户名')
2. forms组件只会自动帮你渲染获取用户输入的标签(input select radio checkbox),form只渲染获取用户数据的标签 不渲染提交按钮 需要我们自己编写
""" def index(request): # 1 直接生成一个不穿参数的form对象 form_obj = MyForm() # 2 直接将该空对象传递给html页面 return render(request,'index.html',locals()) # 前端利用空对象做渲染的标签的方式第一种渲染方式:代码书写极少,封装程度太高 不便于后续的扩展 一般情况下只在本地测试使用
{{ form_obj.as_p }} {{ form_obj.as_ul }} {{ form_obj.as_table }}
第二种渲染方式:可扩展性很强 但是需要书写的代码太多 一般情况下不用
{{ obj.username }}
#可实现按住姓名,光标自动跳到input框{{ form_obj.password.label }}:{{ form_obj.password }}
{{ form_obj.email.label }}:{{ form_obj.email }}
第三种渲染方式(推荐使用):代码书写简单 并且扩展性也高
{% for foo in form_obj %}
{{ foo }} # 融合了方式1和方式2的优势(推荐使用)
{% endfor %}
4.form组件提示信息
浏览器会自动帮你校验数据 但是前端的校验弱不禁风
如何让浏览器不做校验,添加novalidate,前端不校验数据
"""
1.必备的条件 get请求和post传给html页面对象变量名必须一样
2.forms组件当你的数据不合法的情况下 会保存你上次的数据 让你基于之前的结果进行修改
更加的人性化
"""
针对错误的提示信息还可以自己自定制
class MyForm(forms.Form): # username字符串类型最小3位最大8位 username = forms.CharField(min_length=3,max_length=8,label='用户名', error_messages={ 'min_length':'用户名最少3位', 'max_length':'用户名最大8位', 'required':"用户名不能为空" } ) # password字符串类型最小3位最大8位 password = forms.CharField(min_length=3,max_length=8,label='密码', error_messages={ 'min_length': '密码最少3位', 'max_length': '密码最大8位', 'required': "密码不能为空" } ) # email字段必须符合邮箱格式 xxx@xx.com email = forms.EmailField(label='邮箱', error_messages={ 'invalid':'邮箱格式不正确', 'required': "邮箱不能为空" } )
# 正则校验 from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( validators=[ RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], )
6..钩子函数(HOOK)
钩子函数 在类里面书写方法即可
在特定的节点自动触发完成响应操作
钩子函数在forms组件中就类似于第二道关卡,能够让我们自定义校验规则
在forms组件中有两类钩子
1.局部钩子
当你需要给单个字段增加校验规则的时候可以使用
2.全局钩子
当你需要给多个字段增加校验规则的时候可以使用
1.局部钩子
报错方式一:self.add_error
报错方式二:raise ValidationError(一般不用,了解即可)
from django import forms
from django.core.validators import RegexValidator
class MyForm(forms.Form):
username=forms.CharField(min_length=3,max_length=8,label="姓名",error_messages={"min_length":"最少三位",'max_length':"最多8位","requered":"不能为空"})
password=forms.CharField(min_length=3,max_length=8,label="密码",error_messages={"min_length":"最少三位",'max_length':"最多8位","requered":"不能为空"})
email=forms.EmailField(label="邮箱",error_messages={"invalid":"邮箱格式不正确"})
# 钩子函数(基本校验规则完毕之后 产生了cleaned_data数据后才会执行钩子函数) # 局部钩子(单个字段校验):校验用户名是否已存在 def clean_username(self): # 获取用户名数据 username = self.cleaned_data.get('username') # 校验用户名是否已存在 if username == 'jason': # 添加用户名提示信息 self.add_error('username', '用户名已存在') # raise ValidationError('真的可以被捕获吗?') return username #将钩子函数勾出来的数据再放回去
2.全局钩子
使用self.add_error
使用raise ValidationError无效
# 全局钩子(多个字段校验):校验密码与确认密码是否一致 def clean(self): # 获取密码 password = self.cleaned_data.get('password') # 获取确认密码 confirm_password = self.cleaned_data.get('confirm_password') # 比对密码是否一致 if not password == confirm_password: # 添加提示信息 self.add_error('confirm_password', '两次密码不一致') return self.cleaned_data #将钩子函数勾出来的数据再放回去
7.forms组件其他参数及补充知识点
label 字段名
error_messages 自定义报错信息
initial 默认值
required 控制字段是否必填
widget=forms.widgets.PasswordInput() #widget既可以修改input框的type类型,还可以操作标签的属性
""" 1.字段没有样式 2.针对不同类型的input如何修改 text password date radio checkbox ... """ widget=forms.widgets.PasswordInput(attrs={'class':'form-control c1 c2'}) # 多个属性值的话 直接空格隔开即可
# 第一道关卡里面还支持正则校验 validators=[ RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头') ]
其他类型渲染 详见: https://www.cnblogs.com/Dominic-Ji/p/9240365.html
# radio gender = forms.ChoiceField( choices=((1, "男"), (2, "女"), (3, "保密")), label="性别", initial=3, widget=forms.widgets.RadioSelect() ) # select hobby = forms.ChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "排球"),), label="爱好", initial=3, widget=forms.widgets.Select() ) # 多选 hobby1 = forms.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "排球"),), label="爱好", initial=[1, 3], widget=forms.widgets.SelectMultiple() ) # 单选checkbox keep = forms.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput() ) # 多选checkbox hobby2 = forms.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "排球"),), label="爱好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple() )
组件的参数配置
class Ret(Form): name = forms.CharField(max_length=10, min_length=2, label='用户名', error_messages={'required': '该字段不能为空', 'invalid': '格式错误', 'max_length': '太长', 'min_length': '太短'}, widget=widgets.TextInput(attrs={'class':'form-control'})) pwd = forms.CharField(max_length=10, min_length=2, widget=widgets.PasswordInput(attrs={'class':'form-control'})) email = forms.EmailField(label='邮箱', error_messages={'required': '该字段不能为空', 'invalid': '格式错误'})
8.forms组件源码探索
""" 切入点: form_obj.is_valid() """ def is_valid(self): """ Returns True if the form has no errors. Otherwise, False. If errors are being ignored, returns False. """ return self.is_bound and not self.errors # 如果is_valid要返回True的话 那么self.is_bound要为True self.errors要为Flase self.is_bound = data is not None or files is not None # 只要你传值了肯定为True @property def errors(self): "Returns an ErrorDict for the data provided for the form" if self._errors is None: self.full_clean() return self._errors # forms组件所有的功能基本都出自于该方法 def full_clean(self): self._clean_fields() # 校验字段 + 局部钩子 self._clean_form() # 全局钩子 self._post_clean()
Form那些事儿(了解)
常用字段与插件
创建Form类时,主要涉及到 【字段】 和 【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML;
initial
初始值,input框里面的初始值。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用户名", initial="张三" # 设置默认值 ) pwd = forms.CharField(min_length=6, label="密码") 复制代码
error_messages
重写错误信息。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用户名", initial="张三", error_messages={ "required": "不能为空", "invalid": "格式错误", "min_length": "用户名最短8位" } ) pwd = forms.CharField(min_length=6, label="密码")
password
class LoginForm(forms.Form): ... pwd = forms.CharField( min_length=6, label="密码", widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) )
radioSelect
单radio值为字符串
class LoginForm(forms.Form): username = forms.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() )
单选Select
class LoginForm(forms.Form): ... hobby = forms.ChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ), label="爱好", initial=3, widget=forms.widgets.Select() )
多选Select
class LoginForm(forms.Form): ... hobby = forms.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ), label="爱好", initial=[1, 3], widget=forms.widgets.SelectMultiple() )
单选checkbox
class LoginForm(forms.Form): ... keep = forms.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput() )
多选checkbox
class LoginForm(forms.Form): ... hobby = forms.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "双色球"),), label="爱好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple() )
choice字段注意事项
在使用选择标签时,需要注意choices的选项可以配置从数据库中获取,但是由于是静态字段 获取的值无法实时更新,需要重写构造方法从而实现choice实时更新。
方式一:
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 = ((1, '上海'), (2, '北京'),) # 或 self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')
方式二:
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()) # 单选
Django 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类型
自定义验证函数
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 PublishForm(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(required=False, error_messages={'required': u'邮箱不能为空','invalid': u'邮箱格式错误'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))