django_form组件 整理

'''
django—form组件
作用1:页面标签渲染 form = register_form()
作用2:数据校验(form需要字典类型的数据,request.POST就是类似字典类型的数据) form = register_form(data=request.POST)
作用3:错误信息的渲染 form组件,会把错误的字段信息添加到errors中,正确的添加到cleaned_data中

'''
# 1. 快速使用form form组件+form表单
# url.py # 注册功能 url(r'^register.html/', account.register, name='register'), # form组件+form表单 from django import forms from django.core.validators import RegexValidator from django.core.exceptions import ValidationError class register_form(forms.Form): username = forms.CharField( min_length=6, # 设置最小长度 max_length=12, # 设置最大长度 label="用户名", # 设置标签名 # 错误信息提示设置 error_messages={ "min_length": "用户名不能少于6位", "max_length": '用户名不能超过12位', "required": "用户名不能为空" }, # 插件设置 widget=forms.widgets.TextInput( attrs={"class": "form-control", 'xxx': 'c1'} # 给生成的标签添加属性 form-control-- bootstrap样式 ) ) # 密码 password = forms.CharField( label="密码", min_length=6, error_messages={ "required": "密码不能为空", 'min_length': '密码不能少于6位' }, widget=forms.widgets.PasswordInput( attrs={'class': 'form-control'}, # 给生成的标签添加属性 form-control-- bootstrap样式 render_value=True # 返回报错信息的时候要不要展示密码 ) ) # 二次密码校验 re_password = forms.CharField( label="确认密码", min_length=6, error_messages={ "required": "确认密码不能为空", 'min_length': '确认密码不能少于六位' }, widget=forms.widgets.PasswordInput( attrs={'class': 'form-control'}, # 给生成的标签添加属性 form-control-- bootstrap样式 render_value=True # 返回报错信息的时候要不要展示密码 ) ) # 电话号码 phone = forms.CharField( label="手机号", error_messages={ "required": "手机号不能为空" }, # 调用Form组件中的验证器来校验手机号 validators=[RegexValidator(r'1[0-3][0-9]{9}', '手机号格式不正确')], widget=forms.widgets.TextInput( attrs={'class': 'form-control'}, # 给生成的标签添加属性 form-control-- bootstrap样式 ) ) # 邮箱 email = forms.CharField( label="邮箱", error_messages={ "required": "邮箱不能为空", }, # 调用Form组件中的验证器来校验邮箱 validators=[RegexValidator(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', "邮箱格式不正确")], widget=forms.widgets.TextInput( attrs={'class': 'form-control'}, # 给生成的标签添加属性 ) ) # 局部钩子 通过自定义一个clean_字段名的方法实现对Form表单特定字段的校验 # 一个字段校验全部完成后,在继续校验另一个 def clean_username(self): # 从cleaned_data中取出想要的数据 username = self.cleaned_data.get("username") if "2b" in username: # 错误就抛异常 raise ValidationError("不符合社会主义核心价值观!") return username # 通过Form表单的全局钩子函数来验证两次输入的密码是否正确 # 该clean方法, 在每个字段都校验通过之后才调用执行 # raise ValidationError self.add_error() 前者不会把错误的键值对,放回cleaned_data字典中,后者会放回cleaned_data字典中 def clean(self): password = self.cleaned_data.get('password') re_password = self.cleaned_data.get('re_password') if password == re_password: # 判断正确就返回校验过后的数据 return self.cleaned_data self.add_error('re_password', '两次密码输入不一致') # view.py from django.shortcuts import HttpResponse, render, redirect from app01.form.account import register_form def register(request): '''验证码登录''' if request.method == 'GET': form = register_form() return render(request, 'register.html', locals()) form = register_form(data=request.POST) if form.is_valid(): # 数据保存 instance当前创建s的对象 instance = models.user.object.create(**form.cleaned_data) return redirect('home') return render(request, 'register.html', locals())
当提交表单时,浏览器不对表单数据(输入)进行验证:
<form action="" method="post" novalidate>
    {% for field in form %}
        <!--field.label 先在form中找----register_form类中找label-----都有没有就是数据库,orm的字段名字(username)----->
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {{ field }}
    {% endfor %}
</form>

 

1、Django内置字段:
Field
    required=True,               是否允许为空
    widget=None,                 HTML插件
    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=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类型

三 、Django内置插件
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
四 常用字段与插件
1、initial
初始值,input框里面的初始值。
class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="王飞"  # 设置默认值
    )
    pwd = forms.CharField(min_length=6, label="密码")

2、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="密码")

3、password
class LoginForm(forms.Form):
    pwd = forms.CharField(
        min_length=6,
        label="密码",
        widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)
    )

4、radioSelect(生成的是input标签)
class LoginForm(forms.Form):
    gender = forms.fields.ChoiceField(
        choices=((1, "男"), (2, "女"), (3, "保密")),
        label="性别",
        initial=3,//默认值
        widget=forms.widgets.RadioSelect()
    )
5、单选Select(生成select标签)
class LoginForm(forms.Form):
    hobby = forms.fields.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=3,
        widget=forms.widgets.Select()
    )
6、多选Select(生成的是select标签)
class LoginForm(forms.Form):
    hobby = forms.fields.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.SelectMultiple()
    )
7、单选checkbox(生成的是input标签)
class LoginForm(forms.Form):
    keep = forms.fields.ChoiceField(
        label="是否记住密码",
        initial="checked",
        widget=forms.widgets.CheckboxInput()
    )
8、多选checkbox(生成的是input标签)
class LoginForm(forms.Form):
        hobby = forms.fields.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
        label="爱好",
        initial=[1, 3],
        widget=forms.widgets.CheckboxSelectMultiple()
    )

 

 

五
注意:关于choice的注意事项:在使用选择标签时,需要注意choices的选项可以从数据库中获取,但是由于是静态字段 获取的值无法实时更新,那么需要自定义构造方法从而达到此目的。
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')
六 Form表单的用户数据验证方式:
导入方式:from django.core.validators import RegexValidator
基本格式:validators=[RegexValidator(正则表达式, "错误提示"),]

 email = forms.CharField(
        label="邮箱",
        error_messages={
            "required": "邮箱不能为空",
        },
        # 调用Form组件中的验证器来校验邮箱
        validators=[RegexValidator(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', "邮箱格式不正确")],
        widget=forms.widgets.TextInput(
            attrs={'class': 'form-control'},  # 给生成的标签添加属性
        )
    )
七
Form的进阶骚操作
1、批量添加样式:
通过重写form类的init方法来实现。
class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="用户名",
        initial="王飞",
        error_messages={
            "required": "不能为空",
            "invalid": "格式错误",
            "min_length": "用户名最短8位"
        }
    ...

    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、Django 内置的把ORM对象转换成字典的工具函数:

from django.forms.models import model_to_dict

//book_obj为根据条件在数据库中查到的对象
//obj_dict是book_obj对象再数据库中对应的字段和值组成的键值对字典
obj_dict = model_to_dict(book_obj)
//form_obj通过initial设置初始化的值,例如,图书管理系统中的编辑书籍功能,
//点击编辑后跳转到编辑书籍页面,跳转后需要用要编辑的书籍信息填充页面对应信息。
form_obj = forms.BookForm(initial=obj_dict)
    

 

posted @ 2021-10-16 22:29  mofr  阅读(35)  评论(0)    收藏  举报