forms组件
需求示例:获取用户输入 后端判断用户输入的内容是否合法,如果不合法前端渲染对应的错误信息
传统:
def register(request): back_dic = {'username': '', 'password': ""} if request.method == 'POST': username = request.POST.get('username') pwd = request.POST.get('password') if '666' in username: res = "不能有666" back_dic['username'] = res if pwd == "123": res = "密码太简单" back_dic['password'] = res return render(request, 'reg.html', locals())
html:
</head> <body> <form action="" method="post"> {% csrf_token %} <p><input type="text" name="username"> <span>{{ back_dic.username }}</span> </p> <p><input type="text" name="password"> <span>{{ back_dic.password }}</span> </p> <input type="submit"> </form> </body> </html>
用forms组件来实现:校验数据、渲染页面、展示提示信息
一、校验数据、【前后端都可以校验数据,前端可以没有,但是后端一定要有】
1.校验数据,需要一个类,继承forms.Form
from django import forms class Myform(forms.Form): username = forms.CharField(max_length=8) password = forms.CharField(max_length=6, min_length=3) email = forms.EmailField()
2. 给forms组件传参数(字典的形式)
obj = views.Myform({'username': 'egion', 'passowrod': '123'})
3.查看数据校验结果
obj.is_valid()
4. 查看干净的数据
obj.cleaned_data ==> 正确的以字典形式放入{'username': 'egondsb2', 'password': '123'}
5. 查看不正确的数据
obj.errors ==> 错误的放入{'password': ['Ensure this value has at least 3 characters (it has 2).'],
'email': ['This field is required.']}
from app01 import views obj = views.Myform({"username":"egondsb", "password": "123"}) obj.is_valid() False obj.cleaned_data {'password': '123'} obj.errors {'username': ['Ensure this value has at most 6 characters (it has 7).'], 'email': ['This field is required.']}
ps: forms组件中所有的字段默认都是必填的(不能为空)
在数据都满足forms组件校验规则的情况下,多传的数据不作校验,
补充:正则校验数据
from django.core.validators import RegexValidator
phone = forms.CharField(validators=[RegexValidator(r'^[0-9]+$', '请输入数字'),
RegexValidator(r'^159[0-9]+$', '必须以159开头')])
RegexValidator验证器
自定义验证函数
二. 渲染页面、 forms组件只能帮你渲染 获取用户输入(输入框 、选择框 、下拉框 。。。) 提交按钮也得自己写
前端页面识别到是forms组件时,也会校验数据长度,
form表单取消前端校验的提示信息:<form action="/reg1/" method="post" novalidate>
initial 初始值, input框里面的初始值
views:
def reg1(request): form_obj = Myform() return render(request, 'reg1.html', locals())
1.第一种渲染页面的方式【扩展性不高,本地测试】 as_p 、| as_ul
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>forms第一种渲染标签的方式</p> {# {{ form_obj.as_p }} p标签包裹着#} {{ form_obj.as_ul }} li标签包裹着 {#lable展示的信息默认情况下是字段名首字母大写#} </form> </body> </html>
2. 第二种,输入框与label名需自己写,缺点是,当字段比较多时,需要一个个的写,麻烦!包裹p标签
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title</title> </head> <body> <form action="" method="post"> <p>forms第二种渲染标签的方式</p> <p> {{ form_obj.username.label }}{{ form_obj.username }} {# forms对象点字段名拿到的是对应的输入框 #} </p> <p> {{ form_obj.password.label }}{{ form_obj.password }} {# forms对象点字段名拿到的是对应的输入框 #} </p> </form>
3.第三种,常用方式
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title</title> </head> <body> <form action="" method="post" novalidate> {% csrf_token %} {% for foo in form_obj %} <p>{{ foo.label }}{{ foo }} <span>{{ foo.errors.0 }}</span> </p> {% endfor %} <input type="submit"> </form> </body> </html>
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类型
三.展示信息
1. label名,错误息信, 密码密文【from django.forms import widgets】,等可以在类中先定义
from django import forms from django.forms import widgets class Myform(forms.Form): username = forms.CharField(max_length=8, label="用户名", initial="张三", error_messages={"required": "用户名不能为空", "max_length": "用户名长度不能超过8位"}) password = forms.CharField(max_length=6, min_length=3, widget=forms.widgets.PasswordInput(attrs={"class": "form-control c1"}), error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式不正确"}) email = forms.EmailField()
choice字段、 多选checkbox、单选select、radioSelect、password
class Myform2(forms.Form): gender = forms.fields.ChoiceField( choices=((1, "男"), (2, "女"), (3, "保密")), label="性别", initial=3, widget=forms.widgets.RadioSelect() ) hobby = forms.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "双色球"),), label="爱好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple() ) keep = forms.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput() ) hobby1 = forms.ChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ), label="爱好", initial=3, widget=forms.widgets.Select() ) username = forms.CharField( min_length=8, label="用户名", initial="张三", error_messages={ "required": "不能为空", "invalid": "格式错误", "min_length": "用户名最短8位" } ) def reg2(request): myform2 = Myform2() if request.method == "POST": myform2 = Myform2(request.POST) if myform2.is_valid(): print(myform2.cleaned_data) return render(request, "reg2.html", locals())
在django中测试脚本:
1.新建一个test文件:
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day66ajaxformdata.settings") import django django.setup() # 将要测试的代码导入 from app01 import models print(models.Userinfo.objects.all())
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day66ajaxformdata.settings") import django django.setup() # 将要测试的代码导入 # from app01 import models # print(models.Userinfo.objects.all()) from app01 import views obj = views.Myform({'username': "egon", "password": '123'}) print(obj.is_valid())
2. python console 中测试,直接导入需要测试的文件,下面以测试上面forms组件为例
python Console中
from app01 import views obj = views.Myform({"username":"egondsb", "password": "123"}) obj.is_valid() # 校验数据结果 False obj.cleaned_data {'password': '123'} obj.errors {'username': ['Ensure this value has at most 6 characters (it has 7).'], 'email': ['This field is required.']}
forms组件的钩子函数 Hook方法【在form类中写钩子函数】
数据校验顺序:先校验字段中的条件,再走钩子函数规则
局部钩子【校验单个字段】 : 在用户名中不能有666字样
from django import forms from django.forms import widgets from django.core.validators import RegexValidator class Myform(forms.Form): username = forms.CharField(max_length=8, label="用户名", initial="张三", error_messages={"required": "用户名不能为空", "max_length": "用户名长度不能超过8位"}) password = forms.CharField(max_length=6, min_length=3, widget=forms.widgets.PasswordInput(attrs={"class": "form-control c1"}), error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式不正确"}) email = forms.EmailField() phone = forms.CharField(validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '必须以159开头')]) def clean_username(self): # 用户名不能有666 username = self.cleaned_data.get('username') if "666" in username: self.add_error('username', '光喊666是不行的') return username
全局钩子【校验多个字段】:两次密码需一致
from django import forms from django.forms import widgets from django.core.validators import RegexValidator class Myform(forms.Form): username = forms.CharField(max_length=8, label="用户名", initial="张三", error_messages={"required": "用户名不能为空", "max_length": "用户名长度不能超过8位"}) password = forms.CharField(max_length=6, min_length=3, widget=forms.widgets.PasswordInput(attrs={"class": "form-control c1"}),) confirm_password = forms.CharField(max_length=8, min_length=3, label="确认密码", widget=forms.widgets.PasswordInput(attrs={"class": "form-control c1"})) email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式不正确"}) phone = forms.CharField(validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '必须以159开头')]) def clean_username(self): # 用户名不能有666 username = self.cleaned_data.get('username') if "666" in username: self.add_error('username', '光喊666是不行的') return username def clean(self): password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password != confirm_password: self.add_error("confirm_password", "两次密码不一致") return self.cleaned_data