Django-Form组件
Form组件
Form组件的作用:
对前段Form表单POST的数据进行格式效验
常用参数:
-
is_valid():如果Form表单POST的数据都能通过,就会返回True,否则返回Flase
-
cleared_data: 数据效验通过就会以字典的形式存储在里面
-
errors:存储错误字段和信息 。表面是HTML标签类型,实际上是字典
示例:注册页面
views视图函数:
from django.shortcuts import render,HttpResponse
from django import forms
# Create your views here.
class UserForm(forms.Form):
user = forms.CharField(min_length=4)
pwd = forms.CharField(min_length=4)
r_pwd = forms.CharField(min_length=4)
email = forms.EmailField(max_length=32)
tel = forms.IntegerField()
addr = forms.CharField(max_length=32)
def reg(request):
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
# <ul class="errorlist"><li>pwd<ul class="errorlist"><li>Ensure this value has at least 4 characters (it has 3).</li></ul></li></ul>
print(type(form.errors)) # <class 'django.forms.utils.ErrorDict'>
print(type(form.errors.get("pwd"))) # ErrorList ["错误信息",] --> <class 'django.forms.utils.ErrorList'>
print(form.errors.get("pwd")[0]) # ErrorList ["错误信息",] ---> Ensure this value has at least 4 characters (it has 3).
return HttpResponse("OK")
return render(request,"reg.htm
html模板页面
<form method="post">
{% csrf_token %}
<p>user<input type="text" name="user"></p>
<p>pwd<input type="password" name="pwd"></p>
<p>r_pwd<input type="password" name="r_pwd"></p>
<p>email<input type="email" name="email"></p>
<p> tel<input type="tel" name="tel"></p>
<p> addr<input type="text" name="addr"></p>
<input type="submit" >
模板的渲染方式一:
视图函数页面:
form = UserForm() # 实例化 然后传入模板中调用
eturn render(request,"reg.html",locals())
HTML模板页面:
{# 使用Formu组件创建输入框 #}
<form method="post">
{% csrf_token %}
<p>user{{form.user}}</p>
<p>pwd{{form.pwd}}</p>
<p>r_pwd{{form.r_pwd}}</p>
<p>email{{form.email}}</p>
<p>tel{{form.tel}}</p>
<p>addr{{form.addr}}</p>
<input type="submit" >
</form>
模板渲染效果:
模板的渲染方式二:
直接调用UserForm实例化对象的属性,推荐使用
<p>使用Formu组件渲染方式二 </p>
<form method="post">
{% csrf_token %}
{% for form_obj in form %}
<div>
<label for="">{{ form_obj.label }}</label>
{{ form_obj }}
</div>
{% endfor %}
<input type="submit" >
</form>
模板渲染效果:
如果想更改 input标签前面的名字,可以在类 UserForm里设置lable属性即可,示例:
class UserForm(forms.Form):
user = forms.CharField(min_length=4,label="用户名")
pwd = forms.CharField(min_length=4,label="设置想要的值")
r_pwd = forms.CharField(min_length=4)
email = forms.EmailField(max_length=32)
tel = forms.IntegerField()
addr = forms.CharField(max_length=32)
渲染效果:
模板的渲染方式三:
使用UserForm对象的属性:
1. as_p:固定样式: 标签属性不可更改
<p><label for="id_user">User:</label> <input type="text" name="user" minlength="4" required="" id="id_user"></p>
2. as_ul: 固定样式: 标签属性不可更改
<li><label for="id_user">User:</label> <input type="text" name="user" minlength="4" required="" id="id_user"></li>
模板渲染效果:
实现重置和显示错误信息
视图页面:
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
return render(request, "reg.html", locals()) # 添加个返回值,将已有数据的UserForm的对象传入模板中
模板页面:
<p>使用For组件渲染方式一 </p>
<form method="post">
{% csrf_token %}
<p>user{{form.user}}</p><span>{{ form.user.errors.0 }}</span>
<p>pwd{{form.pwd}}</p><span>{{ form.pwd.errors.0 }}</span>
<p>r_pwd{{form.r_pwd}}</p><span>{{ form.r_pwd.errors.0 }}</span>
<p>email{{form.email}}</p><span>{{ form.email.errors.0 }}</span>
<p>tel{{form.tel}}</p><span>{{ form.tel.errors.0 }}</span>
<p>addr{{form.addr}}</p><span>{{ form.addr.errors.0 }}</span>
<input type="submit" >
</form>
给Form组件设置标签类型,增加标签属性,自定义错误信息
只需在类“UserForm”中定义相关属性即可:
1.widget=forms."标签类型"(attr={"属性":"值",})
2.error_messages={"requied":"不能为空属性值","invalid":"无效的属性值",}
示例如下:
class UserForm(forms.Form):
user = forms.CharField(min_length=4,label="用户名",error_messages={"requied":"该字段不能为空","invalid":"无效的",},widget=forms.TextInput(attrs={"class":"form-control"}))
pwd = forms.CharField(min_length=4,label="密码",widget=forms.PasswordInput(attrs={"class":"form-control"}))
r_pwd = forms.CharField(min_length=4,label="确认密码",widget=forms.PasswordInput(attrs={"class":"form-control"}))
email = forms.EmailField(max_length=32,label="邮箱",widget=forms.PasswordInput(attrs={"class":"form-control"}))
tel = forms.IntegerField(label="手机号",widget=forms.TextInput(attrs={"class":"form-control"}))
addr = forms.CharField(max_length=32,label="地址",widget=forms.TextInput(attrs={"class":"form-control"}))
效果图:
局部钩子
对Form表单的每个字段进行逐个检测
示例:对用户名,手机号进行检测判断
# 局部钩子
def clean_user(self):
'''
对输入的用户名判断是否已存在
:return:
'''
print(self.cleaned_data)
# 获取效验过字段的clear_data中的数据
user = self.cleaned_data["user"]
# 判断用户名是否存在
ret = UserInfo.objects.filter(user=user).first()
# 对数据库查询结果进行判断
if not ret: # 不存在即为False,返回对应值
return self.user
else: # 存在报错
raise ValidationError("该用户已存在")
def clean_tel(self):
'''
对手机号进行格式判断
:return:
'''
tel = self.cleaned_data["tel"]
print(tel)
# 对手机号长度进行判断
if len(tel) == 11:
return self.tel
else:
raise ValidationError("手机号格式错误")
效果图:
全局钩子
对Form表单的所有字段进行全局检测
示例:对两次密码进行检测判断
HTML模板:
<p>使用For组件渲染方式一 </p>
<form method="post">
{% csrf_token %}
<p>user{{form.user}}</p><span class="errors pull-right">{{ form.user.errors.0 }}</span>
<p>pwd{{form.pwd}}</p><span class="errors pull-right">{{ form.pwd.errors.0 }}</span>
<p>r_pwd{{form.r_pwd}}</p><span class="errors pull-right">{{ form.r_pwd.errors.0 }}</span><span class="errors pull-right">{{ errors.0 }}</span>
<p>email{{form.email}}</p><span class="errors pull-right">{{ form.email.errors.0 }}</span>
<p>tel{{form.tel}}</p><span class="errors pull-right">{{ form.tel.errors.0 }}</span>
<p>addr{{form.addr}}</p><span class="errors pull-right">{{ form.addr.errors.0 }}</span>
<input type="submit" >
</form>
视图函数:
def reg(request):
print(request.POST)
print(type(request.POST.get("tel")))
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
# 全局钩子错误
errors = form.errors.get("__all__")
print(errors[0]) # 两次密码不一致
效果图: