django from验证组件

from django.shortcuts import render,redirect


from django.forms import  Form,fields
class loginForm(Form):
#自定义正则规则, username
= fields.CharField(max_length=16,min_length=6,required=True,error_messages={'max_length':'太长了'}) password = fields.CharField(max_length=16, min_length=6, required=True, error_messages={'max_length': '太太长了了'}) # Create your views here. def test(request): if request.method =='GET': return render(request, 'login.html') else: obj = loginForm(request.POST) #创建Form类的对象时,需要传入待匹配的数据 v = obj.is_valid() #开始将提交的数据与class定义的规则进行匹配,返回true或者false if v==True: print(obj.cleaned_data) #正确的信息,字典形式 return redirect('http://www.baidu.com') else: print(obj.errors['username'][0]) #错误信息,字典形式 return render(request, 'login.html',{'obj':obj})

 

前端html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <form method="POST" action="/test/">
            {% csrf_token %}
            <p>
                用户名:<input type="text" name="username"/>{{ obj.errors.username.0 }}
            </p>
            <p>
                密码:<input type="text" name="password"/>
            </p>
            <input type="submit" value="登陆"/>
        </form>
    </div>
</body>
</html>

 

posted @ 2019-01-26 15:08  小胡子oYi  阅读(122)  评论(0编辑  收藏  举报