一、概述
在HTML页面中,利用form表单向后端提交数据时,需要编写input等输入标签并用form标签包裹起来,与此同时,在很多应用场景之下需要对用户输入的数据校验,例如注册登录页面中,校验用户注册时输入的用户名是否合法或者该用户是否被注册等并弹出相应的提示信息
Django内的form组件就是为了实现这些功能:
1)生成HTML标签
2)对提交的数据进行校验
3)当数据校验等情况下保存上次输入的内容
在生产场景,前后端都应该进行数据校验
二、应用
1.常用字段与插件
在APP中新建的forms.py文件中,字段用于对数据的校验,插件用于自动生成HTML标签
1)initial,设置input中的初始值
error_messages,对当前字段不符合指定的规则时,重写错误信息
password,指定input输入框的输入类型
password = forms.CharField(
label="密码",
# initial 设置初始值
initial="123456",
# 字段规则,约束条件
min_length=6,
max_length=64,
# 重写错误信息
error_messages={
"required": "密码不能为空",
"min_length": "密码至少6个字符",
"max_length": "密码最多64个字符",
},
# PasswordInput 密码类型
widget=forms.widgets.PasswordInput(
attrs={"class": "form-control"}
)
)
2)单选Select
hobby = forms.fields.ChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "跑步"),), label="爱好", initial=3, widget=forms.widgets.Select )
3)多选Select
hobby = forms.fields.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "跑步"), ), label="爱好", initial=[1, 3], widget=forms.widgets.SelectMultiple )
4)单选Checkbox
keep = forms.fields.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput )
5)多选Checkbox
hobby = forms.fields.MultipleChoiceField( choices=((1, "篮球"), (2, "足球"), (3, "跑步"),), label="爱好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple )
补充:
在使用选择标签时,需要注意choices的选项可以从数据库中获取,但由于是经验字段,获取的值无法实时更新,可通过自定义构造方法,在拉取表单之前将数据库中的数据拉取到自动以的表单内
方法一:在form类中的init中
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()) # 单选
2.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类型
示例:
自定义注册登录表单
from django import forms from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from BBS import models class LoginForm(forms.Form): ''' 自定义登录表单 ''' username = forms.CharField( label="用户名", min_length=2, max_length=12, error_messages={ "required": "用户名不能为空", "min_length": "用户名至少2个字符", "max_length": "用户名最多12个字符", }, widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) password = forms.CharField( label="密码", # initial 设置初始值 initial="123456", min_length=6, max_length=64, error_messages={ "required": "密码不能为空", "min_length": "密码至少6个字符", "max_length": "密码最多64个字符", }, # PasswordInput 密码类型 widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) class RegForm(forms.Form): ''' 自定义注册表单 ''' username = forms.CharField( label="用户名", min_length=2, max_length=12, error_messages={ "required": "用户名不能为空", "min_length": "用户名至少2个字符", "max_length": "用户名最多12个字符", }, widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) password = forms.CharField( label="密码", min_length=6, max_length=64, error_messages={ "required": "密码不能为空", "min_length": "密码至少6个字符", "max_length": "密码最多64个字符", }, widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) re_password = forms.CharField( label="确认密码", min_length=6, max_length=64, error_messages={ "required": "确认密码不能为空", "min_length": "密码至少6个字符", "max_length": "密码最多64个字符", }, widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) phone = forms.CharField( label="手机号码", min_length=11, max_length=11, validators=[ RegexValidator(r'^\d{11}$', "手机号必须十一位,且必须是数字"), RegexValidator(r'^1[356789][0-9]{9}$', "手机号格式不对"), ], error_messages={ "required": "手机号不能为空", "min_length": "手机号码必须11位", "max_length": "手机号码必须11位", }, widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) # 局部钩子 def clean_username(self): username = self.cleaned_data.get("username", "") arlt_list = ["反共", "牛逼", "操你", "滚你"] for i in arlt_list: if i in username: raise ValidationError("用户名中存在敏感字符") elif models.UserInfo.objects.filter(username=username): raise ValidationError("用户名已存在") else: return username # 全局钩子 def clean(self): password = self.cleaned_data.get("password", "") re_password = self.cleaned_data.get("re_password", "") if re_password and password == re_password: return self.cleaned_data else: err_msg = "两次输入的密码不一致" self.add_error("re_password", err_msg) raise ValidationError(err_msg)
通过自定义表单中的钩子函数解读forms中的部分源码
def _clean_fields(self): for name, field in self.fields.items(): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. ''' 对自定义表单中,根据每个自定义的字段中的规则进行校验 1. 校验通过则执行 self.cleaned_data[name] = value 2. 校验失败则执行 self.add_error(name, e) ''' 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 if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e)
if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value
以上源代码中,利用hasattr方法通过反射,针对自定义表单中的某个字段设置自定义校验
高级用法:
1)通过form类中的init方法给字段批量添加样式
class LoginForm(forms.Form): ... def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })
2)注册页面中应用Bootstrap样式以及通过AJAX实现文件上传
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.min.css"> <title>用户注册</title> <style> .reg-form { margin-top: 70px; } #show-avatar { width: 90px; height: 90px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 reg-form"> <form class="form-horizontal" autocomplete="off" novalidate> {% csrf_token %} <div class="form-group"> <label for="{{ form_obj.username.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.username.label }}</label> <div class="col-sm-10"> {{ form_obj.username }} <span class="help-block"></span> </div> </div> <div class="form-group"> <label for="{{ form_obj.password.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.password.label }}</label> <div class="col-sm-10"> {{ form_obj.password }} <span class="help-block"></span> </div> </div> <div class="form-group"> <label for="{{ form_obj.re_password.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label> <div class="col-sm-10"> {{ form_obj.re_password }} <span class="help-block"></span> </div> </div> <div class="form-group"> <label for="{{ form_obj.phone.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.phone.label }}</label> <div class="col-sm-10"> {{ form_obj.phone }} <span class="help-block"></span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">头像</label> <div class="col-sm-10"> <input accept="image/*" type="file" id="id_avatar" name="avatar" style="display: none"> <label for="id_avatar"> <img src="/static/img/default.png" id="show-avatar"> </label> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" class="btn btn-default" id="reg-button">注册</button> </div> </div> </form> </div> </div> </div> <script src="/static/jquery-3.3.1.js"></script> <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script> <script src="/static/setupAjax.js"></script> <script> // 找到注册按钮绑定点击事件 $("#reg-button").click(function () { var dataObj = new FormData(); dataObj.append("username", $("#id_username").val()); dataObj.append("password", $("#id_password").val()); dataObj.append("re_password", $("#id_re_password").val()); dataObj.append("phone", $("#id_phone").val()); // 获取上传头像的对象 dataObj.append("avatar", $("#id_avatar")[0].files[0]); console.log($("#id_avatar")[0].files[0]); $.ajax({ url: "/register/", type: "POST", // processData: false, // contentType: false, data: dataObj, success: function (data) { console.log(data); if (data.code) { // 存在报错信息,则页面的相应位置展示 var errMsgObj = data.data; $.each(errMsgObj, function (k, v) { // k: 字段名 // v:报错信息的数组 // 根据字段名找对应的input标签,将错误信息添加到相应的标签内 $("#id_" + k).next(".help-block").text(v[0]).parent().parent().addClass("has-error"); }) } else { console.log(data.data); location.href = data.data || "/login/" } } }) }); // 给每一个input标签绑定focus事件,移除当前的错误提示信息 $("input.form-control").focus(function () { $(this).next(".help-block").text("").parent().parent().removeClass("has-error"); }); // 头像预览 $("#id_avatar").change(function () { // 找到你选中的那个头像文件 var fileObj = this.files[0]; console.log(fileObj); // 读取文件路径 var fileReader = new FileReader(); fileReader.readAsDataURL(fileObj); // 等图片被读取完毕之后,再做后续操作 fileReader.onload = function () { // 设置预览图片 $("#show-avatar").attr("src", fileReader.result); }; }); </script> </body> </html>