Django:用户登录实例
一、源代码
1,login.html代码(登录界面):
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> <!--引入本地css & js--> <link rel="stylesheet" href="../static/style/app.css"/> </head> <body> <div class="container"> <form class="form-horizontal" action="/login/" method="post"> {% csrf_token %} <div class="control-group"> <label class="control-label" contenteditable="true" for="inputUser">用户</label> <div class="controls"> <input name="inputUser" placeholder="User" type="text" value="lizm" /> </div> </div> <div class="control-group"> <label class="control-label" contenteditable="true" for="inputPassword">密码</label> <div class="controls"> <input name="inputPassword" placeholder="Password" type="password" value="123456" /> </div> </div> <div class="control-group"> <div class="controls"> <label class="checkbox" contenteditable="true"> <input type="checkbox" /> Remember me </label> <button class="btn" contenteditable="true" type="submit">登陆</button> <span style="color:red;"> {{ status }}</span> </div> </div> </form> </div> <script type="text/javascript" src="../static/js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="../static/js/bootstrap.js"></script> </body> </html>
2,views.py代码:
from django.shortcuts import render from blog.models import BlogsPost #导入django的重定向模块 from django.shortcuts import redirect # Create your views here. def blog_index(request): blog_list = BlogsPost.objects.all() return render(request,'index.html',{'blog_list':blog_list}) #Login def login(request): print(request.method) #login.html是用POST方式提交,这里判断是POST方式后,就开始处理玩家的输入 if request.method == "POST"(低版本的用法) if request.POST: #获取login.html用户的输入,取name的值 input_user = request.POST['inputUser'] input_pwd = request.POST['inputPassword'] print("用户名:%s 密码:%s" %(input_user,input_pwd)) if input_user == 'lizm' and input_pwd == '123456': print("登录成功!") #重定向到百度 #return redirect("http://www.baidu.com") #重定向(根据urls.py中的配置的值) return redirect("/blog") else: print("用户名或者密码错误!") #如果用户输入的账号密码不对,login.html页面采用模版来渲染这段错误提示 return render(request,'login.html',{'status':'用户名或者密码错误!'}) return render(request,"login.html")
3,urls.py代码:
from django.conf.urls import * from django.contrib import admin from blog import views urlpatterns = [ url('admin/', admin.site.urls), url(r'^blog',views.blog_index), url(r'^login/',views.login), ]
4,导入bootstrap.css、bootstrap.js、jquery-1.9.1.min.js
二、效果
1,访问http://127.0.0.1:8000/login/
点击“登陆”按钮,效果: