Django的Form主要具备一下两大功能:html
-生成HTML的input标签git
-编写From类正则表达式
- 本身编写一个Form子类,抽象的归纳了想要的表单 数据库
from django.forms import Form from django.forms import widgets from django.forms import fields class MyForm(Form): user = fields.CharField() gender = fields.ChoiceField() city = fields.CharField() pwd = fields.CharField()
- Form组件不生成一个form控件,只能定制其中的input标签django
-包括input标签的type,格式限定,label文本ide
-type函数
插入field.Form 的widget属性 如: user = fields.CharField( initial=2, widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),)) ) TextInput(Input) NumberInput(TextInput) EmailInput(TextInput) URLInput(TextInput) PasswordInput(TextInput) HiddenInput(TextInput) Textarea(Widget) DateInput(DateTimeBaseInput) DateTimeInput(DateTimeBaseInput) TimeInput(DateTimeBaseInput) CheckboxInput Select NullBooleanSelect SelectMultiple RadioSelect CheckboxSelectMultiple FileInput ClearableFileInput MultipleHiddenInput SplitDateTimeWidget SplitHiddenDateTimeWidget SelectDateWidget
-格式限定,先引入from django import formsui
而后,book=forms.ModelChoiceField()this
Field required=True, 是否必须填写, widget=TextInput, HTML插件 hidden_widget = HiddenInput label=None, 用于生成Label标签或显示内容 initial=None, 初始值 help_text='', 帮助信息(在标签旁边显示) error_messages=None, 错误信息 {'required': '不能为空', 'invalid': '格式错误'} show_hidden_initial=False, 是否在当前插件后面再加一个隐藏的且具备默认值的插件(可用于检验两次输入是否一直) 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=Select, 插件,默认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类型 ...
-labelspa
在对应限定类型中的label参数中输入
-提示错误信息,
Form的error_messages中指定 error_messages={'required': '标题不能为空', 'min_length': '标题最少为5个字符', 'max_length': '标题最多为20个字符'}
-标签的class,
在widget的attr参数中写定 如: widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'手机号码'}))
- 生成实例
-form_obj=Myform({}),输入一个字典类型,键值对的键会对应上input标签的name,值会传入其中
class BaseForm(object): # This is the main implementation of all the Form logic. Note that this # class is different than Form. See the comments by the Form class for more # information. Any improvements to the form API should be made to *this* # class, not to the Form class. default_renderer = None field_order = None prefix = None use_required_attribute = True def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} self.auto_id = auto_id if prefix is not None: self.prefix = prefix self.initial = initial or {} self.error_class = error_class # Translators: This is the default suffix added to form field labels self.label_suffix = label_suffix if label_suffix is not None else _(':') self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields) self._bound_fields_cache = {} self.order_fields(self.field_order if field_order is None else field_order) if use_required_attribute is not None: self.use_required_attribute = use_required_attribute # Initialize form renderer. Use a global default if not specified # either as an argument or as self.default_renderer. if renderer is None: if self.default_renderer is None: renderer = get_default_renderer() else: renderer = self.default_renderer if isinstance(self.default_renderer, type): renderer = renderer() self.renderer = renderer
-加入response
- render(request,'',{'form':form_obj}),
-验证用户数据
-接收request数据。
-生成一个自定制的from类
-验证数据,得出一个结果,
- 编写验证规则
- django自带的规则
- 自定义规则
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): phone = fields.CharField(min_length=11,max_length=11, validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], )
validators做用是附加验证
validators数据类型为列表,每一个元素是RegexValidator的实例,第一个参数是正则表达式,第二个参数是抛出的错误信息。
- 自定义逻辑规则:
if data['againpwd'] and data['againpwd'] != data['password']: reg_obj.add_error('againpwd', '两次密码不一致') #实时的加入对应错误信息 errors_dict = {'errors': list(reg_obj.errors)} return render(request, 'register.html', {'regform': reg_obj, 'errors_list': errors_dict})
-局部自定义钩子函数
def clean_username(self): # 函数名和和input框名字同样,只做用于相应字段 print('woshi clean_username') def clean_password(self): print('woshi clean_password') def clean_passworddfsdfs(self): print('woshi clean_passworddfsdfs')
- 验证,得出判断结果
- form_obj.is_vaild()会获得一个布尔型的返回值
- 上一步以前,cleaned_data是没有值的
- 以form形式提交收到错误,而后标红对应input框
- input标签下面errors属性(列表类型)
- 在Html中用模板语言取到错误信息,包括错误input框name和其错误信息
- 使用js取 ,把name作成一个列表,而后用字典的方式送到网页,用js取出,{{errorlist| safe}} js要用safa关键字
- form_obj
-若是结果不对,自动修改input标签样式
- 取到错误信息的name,用js修改
form控件接受数据,提交数据库:一对一提交,以及一对多提交 :
- clean_data 中 一对一关系,ModelChoiceField字段,收到的是一个对应的表的实例
一对多关系,ModelMultipleChoiceField ,收到的是一个Queryset 实例。
- 实际上数据中,多对多关系,会新建一张表,这张表的内容依赖其余两张创建关系的表而存在
- 多对多关系表插入数据必需要在主表插入相应数据以后
- 具体插入使用 主表相应实例对象的多对多字段的add方法
- add方法能够插入对应副表的pk值,pk值列表,副表对象,Queryset对象,Queryset的数据类型是列表,要注明(加*)