from django.forms import Form,fields #注意:username,password必须跟html里面的name='username',name='password'一样 class Login_form(Form): #正则验证:6-16位,不能为空 username = fields.CharField( max_length = 16, min_length = 6, required=True, #当username匹配不成功,显示中文信息 error_messages={ 'max_length':'不能超过16位', 'min_length':'不能小于6位', 'required':'不能为空' } ) # 正则验证:至少6位,不能为空 password = fields.CharField(min_length=6,required=True) def login(request): if request.method == 'GET': return render(request,'login.html') else: obj = Login_form(request.POST)#实例化对象=类(用户所有的请求信息) result = obj.is_valid()#is_valid()返回的结果是True或False if result:#如果验证成功(输入格式正确): print(obj.cleaned_data)#{'username': 'ttttttt', 'password': '1111111'}打印正确信息,字典类型 return redirect('http://www.sogo.com') else: return render(request,'login.html',{'obj':obj})
<form method="post" action="/login"> {% csrf_token %} <p><!--obj.errors是错误信息(字典),username是key,0是索引为0的第一个值--> 用户名: <input type="text" name="username">{{ obj.errors.username.0 }} </p> <p> 密码:<input type="password" name="password">{{ obj.errors.password.0 }} </p> <p> <input type="submit" value="提交"> </p> </form> </body>