1,django目录结构(需要用到的文件用红箭头标记):
2,首先在templates模版目录下创建login.html文件
3,将bootstrap导入到static/plugins目录下 PS:Bootstrap是Twitter推出的一个用于前端开发的开源工具包,有很丰富的前端各种案例
4,首先在templates下创建login.html登陆首页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆</title> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css"></link> </head> <body> <div class="container"> <form class="form-horizontal" action="/login/" method="post"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" name="email" class="form-control" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" name="pwd" class="form-control" placeholder="Password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Sign in</button> <span style="color:red;"> {{ status }}</span> </div> </div> </form> </div> <script type="text/javascript" src="/static/js/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="static/plugins/bootstrap/js/bootstrap.js"></script> </body> </html>
5,先把login.html加到django的路由表里面,django的路由文件是urls.py
from django.conf.urls import include, url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^home/', views.home), url(r'^son/', views.son), url(r'^login/',views.login), ]
6,路由文件添加好后,在vies.py中添加登陆认证逻辑
def login(request): print request.method if request.method == "POST": #login.html是用POST方式提交,这里判断是POST方式后,就开始处理玩家的输入 input_email = request.POST['email'] #获取login.html用户的输入,取name的值 <input type="email" name="email" class="form-control" placeholder="Email"> input_pwd = request.POST['pwd'] #获取login.html用户的输入,取name的值 <input type="password" name="pwd" class="form-control" placeholder="Password"> if input_email == 'lei@qq.com' and input_pwd == "123": from django.shortcuts import redirect #导入django的重定向模块 return redirect("http://www.baidu.com") #重定向到百度 else: return render(request, 'login.html',{'status':'ERROR Incorrect username or password'}) #如果用户输入的账号密码不对,就提示错误信息"ERROR Incorrect username or password" ,login.html页面采用模版来渲染这段错误提示 return render(request,'login.html')
7,验证效果
首先故意输错,看页面提示什么
输入错误的账号密码后,页面提示红色错误
这次输入正确的账号密码,正常是会跳转到http://www.baidu.com 这里就不展示了。