Django之Form组件
目录
- Django之Form组件
- 介绍
- 手动渲染错误信息
- 基于Form组件校验数据
- 重写错误信息
- 用户名与密码
- radioSelect
- 单选Select
- 多选Select
- 单选checkbox
- 多选checkbox
- 前端渲染
介绍
Form组件提供了一种在网页上收集用户输入数据并将其提交到服务器进行处理的机制,这样可以极大的减少书写报错信息时的工作量
手动渲染错误信息
def register(request):
error_msg_dict = {}
if request.method == "POST":
data = request.POST
username = data.get("username")
password = data.get("password")
if username != "aaa":
error = "用户名错误"
error_msg_dict["username_error"] = error
if password != "111":
error = "密码错误"
error_msg_dict["password_error"] = error
return render(request, "register.html", locals())
<form action="" method="post">
<p>
username : <input type="text" name="username">
<span style="color: red">{{ error_msg_dict.username_error }}</span>
</p>
<p>
password : <input type="password" name="password">
<span style="color: red">{{ error_msg_dict.password_error }}</span>
</p>
<input type="submit">
</p>
</form>
基于Form组件校验数据
在app中创建UserForm.py文件
语法和模型层类似,max_length
指定了最大数据长度
from django import forms
class UserForm(forms.Form):
user = forms.CharField(max_length=20,min_length=6)
pwd = forms.CharField(max_length=20,min_length=6)
调用Form组件
def register(request):
if request.method == 'POST' and request.is_ajax():
# data = request.POST
data = json.loads(request.body.decode())
username = data.get('username')
password = data.get('password')
print(username, password)
# 创建Form对象,键是类中定义的参数,值是前端传来的数据
form_obj = UserForm({
'user': username,
'pwd':password,
})
# 校验数据是否合法
print(form_obj.is_valid())
print(f'所有字段{form_obj.changed_data}')
print(f'合法的obj:{form_obj.changed_data}')
print(f'非法的obj:{form_obj.errors}')
state = {'state': 200}
return JsonResponse(state)
return render(request, 'app01/register.html')
打印结果
False
所有字段['user', 'pwd']
合法的obj['user', 'pwd']
非法的obj<ul class="errorlist"><li>user<ul class="errorlist"><li>确保该变量至少包含 6 字符(目前字符数 3)。</li></ul></li><li>pwd<ul class="errorlist"><li>确保该变量至少包含 6 字符(目前字符数 3)。</li></ul></li></ul>
此结果表示user和pwd数据都未达到最低限制长度
重写错误信息
用户名与密码
from django import forms
class UserForm(forms.Form):
user = forms.CharField(max_length=20, min_length=6,
error_messages={
"required": "不能为空",
"invalid": "格式错误",
"max_length": "用户名最长20位",
"min_length": "用户名最短8位"
}
)
pwd = forms.CharField(max_length=20, min_length=6,
error_messages={
"required": "不能为空",
"invalid": "格式错误",
"max_length": "密码最长20位",
"min_length": "密码最短8位"
}
)
radioSelect
单radio值为字符串
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,
widget=forms.widgets.RadioSelect()
)
单选Select
class LoginForm(forms.Form):
...
hobby = forms.ChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
label="爱好",
initial=3,
widget=forms.widgets.Select()
)
多选Select
class LoginForm(forms.Form):
...
hobby = forms.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"), ),
label="爱好",
initial=[1, 3],
widget=forms.widgets.SelectMultiple()
)
单选checkbox
class LoginForm(forms.Form):
...
keep = forms.ChoiceField(
label="是否记住密码",
initial="checked",
widget=forms.widgets.CheckboxInput()
)
多选checkbox
class LoginForm(forms.Form):
...
hobby = forms.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
label="爱好",
initial=[1, 3],
widget=forms.widgets.CheckboxSelectMultiple()
)
前端渲染
forms类
from django import forms
# 按照Django form组件的要求自己写一个类
class UserForm(forms.Form):
name = forms.CharField(label="用户名")
pwd = forms.CharField(label="密码")
views.py
def register(request):
form_obj = MyForm
if request.method == "POST":
# 实例化form对象的时候,把post提交过来的数据直接传进去
form_obj = RegForm(request.POST)
# 校验成功后执行
if form_obj.is_valid():
return HttpResponse("注册成功")
return render(request, "register.html", locals())
前端
<body>
<form action="" method="post" novalidate autocomplete="off">
<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>
<input type="submit" class="btn btn-success" value="注册">
</div>
</form>
</body>