欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django框架首頁(yè)和登錄頁(yè)分離操作示例

 更新時(shí)間:2019年05月28日 09:20:59   作者:學(xué)習(xí)筆記666  
這篇文章主要介紹了Django框架首頁(yè)和登錄頁(yè)分離操作,結(jié)合實(shí)例形式分析了Django框架登錄、驗(yàn)證、跳轉(zhuǎn)首頁(yè)等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Django框架首頁(yè)和登錄頁(yè)分離操作。分享給大家供大家參考,具體如下:

1.登錄模板login.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>用戶登錄</title>
</head>
<body>
  <form method="post">
    <p>用戶名:<input type="text" name="username"></p>
    <p>密碼:<input type="password" name="pwd"></p>
    <p><input type="submit" value="提交"></p>
    <hr>
  </form>
  <p> {{ result }}</p>
</body>
</html>

2.URL設(shè)置

url(r'^login/', "hello.views.login")

表示瀏覽器訪問login,就指向hello應(yīng)用下views文件下login方法

3.在login方法下響應(yīng)login模板和完成登錄功能

def login(request):
  msg = {'result': ''}
  if request.method == 'POST':
    getUserName = request.POST.get('username')
    getPwd = request.POST.get('pwd')
    # 實(shí)例化UserLogin類
    loginObj = UserLogin(getUserName,getPwd)
    if loginObj.isLogin():
      myReponse = HttpResponse("<script>self.location='/index'</script>")
      myReponse.set_cookie('userlogin_username',getUserName,3600)
      return myReponse
    else:
      msg['result'] = '用戶名或密碼錯(cuò)誤'
  myReponse = render_to_response("login.html", msg)
  return myReponse

其中我們使用了UserLogin類,并用此類中的方法完成了用戶是否已經(jīng)登錄的驗(yàn)證。

UserClass.py:

# coding:utf-8
class UserLogin:
  userName = ''
  pwd = ''
  # 構(gòu)造方法
  def __init__(self,username,pwd):
    self.userName = username
    self.pwd = pwd
  # 登錄驗(yàn)證方法
  def isLogin(self):
    if self.userName == 'jack' and self.pwd == '123':
      return True
    else:
      return False

在views.py中使用之前必須要引入:

from UserClass import UserLogin

表示從UserClass中導(dǎo)入U(xiǎn)serLogin。

4.在login方法中,登錄成功就跳轉(zhuǎn)到了首頁(yè),首頁(yè)顯示登錄用戶名

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首頁(yè)</title>
</head>
<body>
  <h2>這是首頁(yè),當(dāng)前登錄用戶是:{{ username }}</h2>
  <p><a href="##" rel="external nofollow" >安裝退出</a></p>
</body>
</html>

def hi(request):
  msg = {'username':'游客'}
  if request.COOKIES.get('userlogin_username') != None :
    msg['username'] = request.COOKIES.get('userlogin_username')
  myReponse = render_to_response("index.html",msg)
  return myReponse

希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論