Django:用戶登錄實例
阿新 • • 發佈:2018-08-07
www. ima red gin urn 如果 wid nta tex
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/
點擊“登陸”按鈕,效果:
Django:用戶登錄實例