Form那些事儿

创建Form类时,主要涉及到 【字段】 和 【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML;

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="密码", //密码框是不可见的 要使用 PasswordInput       widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) )

4:radioSelect

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, // radio 单选框使用RadioSelect方法产生
widget=forms.widgets.RadioSelect()
)

5:单选Select

class LoginForm(forms.Form):
...
hobby = forms.fields.ChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
label="爱好",
initial=3,      // select 单选框使用 Select方法
widget=forms.widgets.Select()
)

6:多选Select

class LoginForm(forms.Form):
...
hobby = forms.fields.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
label="爱好",
initial=[1, 3], // 多选的select 使用的是 SelectMultiple
widget=forms.widgets.SelectMultiple() )

7:单选checkbox

class LoginForm(forms.Form):
...
keep = forms.fields.ChoiceField(
label="是否记住密码",
initial="checked", // 只有一个 CheckBox
widget=forms.widgets.CheckboxInput()
)

8:多选checkbox

class LoginForm(forms.Form):
...
hobby = forms.fields.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
label="爱好",
initial=[1, 3], // 多个checkbox 要使用checkboxSelectMultiple
widget=forms.widgets.CheckboxSelectMultiple()
)

校验

关于手机号码的校验

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator // 需要导入的模块 class MyForm(Form):
user = fields.CharField(
validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^1[3-9][0-9]{9}+$', '数字必须以13到19开头')],
)
05-11 20:41