一、form组件功能
form 组件的主要功能如下:
- 生成页面可用的HTML标签
- 对用户提交的数据进行校验
- form表单提交时,数据出现错误,返回的页面中仍可以保留之前输入的数据
二、使用form组件实现登录校验
views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(
label="账号",
min_length=2,
max_length=16,
required=True,
error_messages={
"min_length": "用户名最少2位",
"max_length": "用户名不能超过16位",
"required": "请输入用户名",
"invalid": "格式错误"
}
)
password = forms.CharField(
label="密码",
min_length=6,
required=True,
error_messages={
"min_length": "密码最少6位",
"required": "请输入密码",
}
)
def login(request):
form_obj = LoginForm()
if request.method == "POST":
form_obj = LoginForm(request.POST)
if form_obj.is_valid():
return HttpResponse("登录成功")
return render(request, "login.html", {"form_obj": form_obj})
login.html(三种渲染方式)
方式1(推荐)
<form action="" method="post" novalidate>
{% csrf_token %}
<div>
<label for="{{ form_obj.username.id_for_label }}">{{ form_obj.username.label }}</label>
{{ form_obj.username }}{{ form_obj.username.errors.0 }}
</div>
<div>
<label for="{{ form_obj.password.id_for_label }}">{{ form_obj.password.label }}</label>
{{ form_obj.password }}{{ form_obj.password.errors.0 }}
</div>
<div>
<label for="form_submit"></label>
<input type="submit" id="form_submit" value="登录">
</div>
</form>
方式2
<form action="" method="post" novalidate>
{{ form_obj.as_p }}
<p>
<label for="form_submit"></label>
<input type="submit" id="form_submit" value="登录">
</p>
</form>
方式3
<form action="" method="post" novalidate>
{% csrf_token %}
{% for field in form_obj %}
<div>
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<div>
<label for="form_submit"></label>
<input type="submit" id="form_submit" value="登录">
</div>
</form>
三、Form组件
创建Form类时,主要涉及到 【字段】 和 【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML。
Django Form 内置字段:
Field
required=True, 是否允许为空
label=None, 用于生成Label标签或显示内容
error_messages=None, 错误信息 {'required': '不能为空', 'invalid': '格式错误'}
initial=None, 初始值
disabled=False, 是否可以编辑
widget=None, HTML插件
validators=[], 自定义验证规则
help_text='', 帮助信息(在标签旁边显示)
localize=False, 是否支持本地化
label_suffix=None, Label内容后缀
show_hidden_initial=False, 是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一致)
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类型(UUID是根据MAC以及当前时间等创建的不重复的随机字符串)
Django Form 内置插件:
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
常用选择插件:
password(额外加的)
from django import forms
from django.forms import widgets
class TestForm(forms.Form):
password = forms.CharField(
label="密码",
min_length=6,
required=True,
widget=widgets.PasswordInput(attrs={"class": "c1"}, render_value=True)
)
单选radio,值为字符串(2种方式)
class TestForm(forms.Form):
gender1 = forms.ChoiceField(
choices=((1, "男"), (2, "女"),(3, "保密")),
initial=3,
widget=widgets.RadioSelect
)
gender2 = forms.CharField(
initial=3,
widget=widgets.RadioSelect(choices=((1, "男"), (2, "女"), (3, "保密"),))
)

单选select,值为字符串(2种方式)
class TestForm(forms.Form):
addr1 = forms.ChoiceField(
choices=((1, "北京"), (2, "上海"), (3, "广州")),
initial=3,
widget=widgets.Select
)
addr2 = forms.CharField(
initial=3,
widget=widgets.Select(choices=((1, "北京"), (2, "上海"), (3, "广州")),)
)

多选select,值为列表
class TestForm(forms.Form):
addr = forms.MultipleChoiceField(
choices=((1, "北京"), (2, "上海"), (3, "广州")),
initial=[1,3,],
widget=widgets.SelectMultiple
)

单选checkbox
class LoginForm(forms.Form):
keep = forms.ChoiceField(
label="是否记住密码",
initial="checked",
widget=widgets.CheckboxInput()
)

多选checkbox,值为列表
class TestForm(forms.Form):
addr = forms.MultipleChoiceField(
choices=((1, "北京"), (2, "上海"), (3, "广州")),
initial=[1, 3,],
widget=widgets.CheckboxSelectMultiple()
)

注意:
在使用选择标签时,需要注意choices的选项可以从数据库中获取,但是由于是静态字段(获取的值无法实时更新),那么需要自定义构造方法从而达到此目的。
方式1(推荐)
# appxx/models.py
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=16)
# appxx/myform/form.py
from django import forms
from django.forms import widgets
from appxx import models
class TestForm(forms.Form):
user_id = forms.IntegerField(
widget=widgets.Select()
)
def __init__(self, *args, **kwargs):
super(TestForm, self).__init__(*args, **kwargs)
self.fields["user_id"].widget.choices = models.User.objects.values_list("id", "name")
# appxx/views.py
from django.shortcuts import render
from appxx.myform.form import TestForm
def test(request):
form_obj = TestForm()
return render(request, "test.html", {"form_obj": form_obj})
<p>{{ form_obj.user_id }}</p>
当数据库发生数据变化时,再次请求时即可得到数据库最新数据,不必重新运行项目。

方式2(不推荐)
使用django提供的 ModelChoiceField 或 ModelMultipleChoiceField 字段来实现。但是,依赖models中的 __str__方法。
具体区别参考上面代码
# appxx/models.py
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=16)
def __str__(self): # 依赖 __str__ 方法
return self.name
# appxx/myform/form.py
from django import forms
from appxx import models
from django.forms import models as form_models
class TestForm(forms.Form):
user_id = form_models.ModelChoiceField(
initial=3,
queryset=models.User.objects.all(),
to_field_name="id"
)

如果没有 __str__ 方法,将显示如下。

四、校验相关
方式1
from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
class RegisterForm(forms.Form):
phone = forms.CharField(
label="手机号码",
required=True,
widget=widgets.TextInput,
error_messages={"required": "请输入手机号码"},
validators=[
RegexValidator(r"(13|14|15|17|18|19)[0-9]{9}", "手机号码格式有误"),
],
)
方式2
import re
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
# 自定义校验规则
def phone_validate(value):
re_phone = re.compile(r"(13|14|15|17|18|19)[0-9]{9}")
if not re_phone.match(value):
raise ValidationError( "手机号码格式有误")
# 使用自定义校验规则
class RegisterForm(forms.Form):
phone = forms.CharField(
label="手机号码",
required=True,
widget=widgets.TextInput,
error_messages={"required": "请输入手机号码"},
validators=[phone_validate,],
)
方式3(form组件的钩子)
# 实例化时(form_obj = XxForm(request.POST))
self.fields = {
"username":"字段规则对象",
"password":"字段规则对象",
}
# 校验时(if form_obj.is_valid():)
self._errors = {}
self.cleaned_data = {}
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
class RegisterForm(forms.Form):
username = forms.CharField(
label="用户名",
required=True,
max_length=16,
widget=widgets.TextInput,
error_messages={
"required": "请输入登录用户名",
"max_length": "用户名过长"
},
)
password = forms.CharField(
label="密码",
required=True,
min_length=6,
widget=widgets.PasswordInput,
error_messages={
"required": "请输入密码",
"min_length": "输入最少6位"
},
)
re_password = forms.CharField(
label="确认密码",
required=True,
widget=widgets.PasswordInput,
error_messages={
"required": "请输入确认密码",
},
)
# 局部钩子
def clean_username(self):
value = self.cleaned_data.get("username")
if "傻逼" in value:
raise ValidationError("敏感词语!")
return value
# 全局钩子
def clean(self):
password = self.cleaned_data.get("password")
re_password = self.cleaned_data.get("re_password")
if password != re_password:
self.add_error("re_password", ValidationError("两次密码不一致!"))
raise ValidationError("两次密码不一致!")
return self.cleaned_data
五、补充
批量添加样式
class RegisterForm(forms.Form):
username = forms.CharField(
label="用户名",
required=True,
max_length=16,
widget=widgets.TextInput,
error_messages={
"required": "请输入用户名",
"max_length": "用户名过长"
},
)
...
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
"class": "form-control"
})
来源:https://www.cnblogs.com/believepd/p/9933586.html