修改 urls.py,添加
path('field.html', views.field),
在 templates 下创建 field.html, 内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/field.html" enctype="multipart/form-data">
<div>f1: <label for="{{ obj.f1.id_for_label }}">{{ obj.f1.label }}</label>
{{ obj.f1.label_tag }}
{{ obj.f1 }}</div>
<div>f3: {{ obj.f3 }}</div>
<div>f4: {{ obj.f4 }}</div>
<div>f5: {{ obj.f5 }}</div>
<div>f6: {{ obj.f6 }}</div>
<div>f7: {{ obj.f7 }}</div>
<div>f8: {{ obj.f8 }}</div>
<input type="submit" value="提交">
</form>
</body>
</html>
修改 views.py
from app01 import forms
def field(request):
if request.method == 'GET':
obj = forms.FieldForm()
return render(request, 'field.html', {'obj': obj})
elif request.method == 'POST':
obj = forms.FieldForm(request.POST, request.FILES)
obj.is_valid()
print(obj.clean())
print(obj.errors.as_json())
return render(request, 'field.html', {'obj': obj})
修改 forms.py
from django.core.validators import RegexValidator
class FieldForm(DForms.Form):
f1 = fields.CharField(
max_length=6, # 最大长度
required=True, # 是否允许为空
initial='World', # 初始值
validators=[RegexValidator(r'^[0-9]+$', '请输入数字', code='e1'), RegexValidator(r'159[0-9]+$', '数字必须以159开头', code='e2')], # 自定义验证规则
error_messages={'required': 'Not null', 'invalid': 'wrong format', 'e1': 'input number', 'e2': 'begin with 159', 'max_length': 'too long'}, # 错误信息
show_hidden_initial=True, # 是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
label='Hello', # 用于生成Label标签或显示内容
disabled=False, # 是否可以编辑
label_suffix=' -->', # Label内容后缀
)
# f2 = fields.RegexField(r'159[0-9]+$')
f3 = fields.FileField()
f4 = fields.ChoiceField(
initial=2,
choices=[(1, '赵四'), (2, '刘能'), (3, '王舞')],
)
f5 = fields.TypedChoiceField(
coerce=lambda x: int(x), # 对选中的每一个值进行一次转换
initial=2,
choices=[(1, '赵四'), (2, '刘能'), (3, '王舞')],
)
f6 = fields.MultipleChoiceField(
initial=[2, 3],
choices=[(1, '赵四'), (2, '刘能'), (3, '王舞')],
)
f7 = fields.SplitDateTimeField()
f8 = fields.FilePathField(
path='app01', # 文件夹路径
recursive=True, # 递归下面的文件夹
allow_folders=True # 允许文件夹
)