连接数据库实现用户的登录验证

1. from app01 import models  导入数据库

2.u = request.POST.get('username')  p = request.POST.get('password')  通过这两步获取用户输入的账号和密码

3.obj = models.UseInfo.object.filter(username=u, password=p).first()   与数据库进行匹配

if obj:  判断用户是否输入的账号密码是否正确

url 文件  设置login和indexURL接口

from django.conf.urls import url
from  app01 import views
urlpatterns = [


    url(r'^login/', views.login),
    url(r'^orm/', views.orm),
    url(r'^index/', views.index)

    # url(r'^detail/', views.detail),
    # url(r'^detail.html-(d+\).html', views.detail, name='indexx'),
    # url(r'^sdaddad/(\d+)/', views.detail, name='indexx'),
]

views文件

def login(request):
    if request.method == 'GET':  #首先先跳转到login.html 文件
        return render(request, 'login.html')  
    elif request.method == 'POST':  #当用户在login文件中提交返回时的结果
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        print(u, p)
        obj = models.Userinfo.objects.filter(username=u, password=p).first()
        print(obj)
        if obj:
           print('1')
           return  redirect('/cmdb/index/')
        else:
            return render(request, 'login.html')

login登录文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="cmdb/login/" method="post" >
        <p>
        <input type="text" name="username">
        <input type="text" name="pwd">
        </p>

        <input type="submit" value="提交">
    </form>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/my-love-is-python/p/9345777.html