1.is_valid()校验机制
def login(request): if request.method == "POST":#POST方法,相当于在登录页提交账号密码 # print("收到的数据:",request.POST) form_obj = LoginForm(request.POST) #与if外的form_obj不同,此包含数据信息,if外的是空对象 #form组件校验功能 # print('111') if form_obj.is_valid(): #is_valid是一个实例方法,由form_obj调用,从Form的父类中得到,返回一个布尔值 #返回数据全部合格,取出合格数据 #print('666') return HttpResponse("success") else: #最少存在一个字段错误 #取出错误信息 # print(form_obj.errors) #{"字段":["","",...]} # print(type(form_obj.errors)) #<class 'django.forms.utils.ErrorDict'> # print(form_obj.errors["user"])#{"user":""} # print("="*120) # print(type(form_obj.errors["user"]))#<class 'django.forms.utils.ErrorList'> # print(form_obj.errors.get("__all__")) all_error = form_obj.errors.get("__all__") return render(request, "login.html", locals()) else:#GET方法,相当于正常访问登录页 form_obj = LoginForm() # get方法,返回一个实例化对象form.obj,把它含有的信息作为一个变量传到obj里 return render(request,"login.html",{"form_obj":form_obj}) # return render(request,"login.html",locals())
2.钩子
class LoginForm(forms.Form): #定义一个类 user = forms.CharField(max_length=12,min_length=5, error_messages={ "required":"不能为空", "min_length":"最小长度为5", }, widget=widgets.Input(attrs={"class": "active"}) ) pwd = forms.CharField(max_length=12,min_length=6, error_messages={ "required":"不能为空", "min_length": "最小长度为6", "invalid":"格式错误", }, widget=widgets.PasswordInput(attrs={"class":"active"}) #密码显示为密文,attrs是属性, ) pwd_tw = forms.CharField(max_length=12,min_length=6, error_messages={ "required":"不能为空", "min_length": "最小长度为6", "invalid":"格式错误", }, widget=widgets.PasswordInput(attrs={"class":"active"}) #密码显示为密文,attrs是属性, ) email = forms.EmailField( error_messages={ "required": "不能为空", "min_length": "最小长度为6", "invalid": "格式错误", }, widget=widgets.EmailInput(attrs={"class":"active"}) )
#校验user字段,自定义字段 #局部钩子的写法: # def clean_user(self): # val = self.cleaned_data.get("user") # # if not val.isdigit(): # return val # else:#用户名如果全部为数字 # raise ValidationError("用户名不能全部为数字") # def clean_pwd(self): # val_pwd = self.cleaned_data.get("pwd")#用键值对self.cleaned_data["user"]方法会报错 # if val_pwd.startswith("root"): # return val_pwd # else: # raise ValidationError("密码必须以root开头") #编写全局钩子 def clean(self): pwd = self.cleaned_data.get("pwd") pwd_tw = self.cleaned_data.get("pwd_tw") if pwd==pwd_tw: return self.cleaned_data else: raise ValidationError("两次密码不一致!")
3.login.html
{# novalidate方法作用是不用浏览器显示提示 #} <form action="" method="post" novalidate> {% csrf_token %} <div> <label for="">用户名:</label> {{ form_obj.user }}<span>{{ form_obj.errors.user.0 }}</span> {# {{ }}是一个模板语言 #} </div> <div> <label for="">密码:</label> {{ form_obj.pwd }}<span>{{ form_obj.errors.pwd.0 }}</span> </div> <div> <label for="">确认密码:</label> {{ form_obj.pwd_tw }}<span>{{ form_obj.errors.pwd_tw.0 }}</span> </div> <div> <label for="">Email:</label> {{ form_obj.email }}<span>{{ form_obj.errors.email.0 }}</span> </div> <input type="submit"> <span style="color: red">{{ all_error.0 }}</span> </form>
想多了解关于form组件的内容,可以访问:https://www.cnblogs.com/linagcheng/p/10015945.html