溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Django框架怎么實現(xiàn)首頁和登錄頁分離

發(fā)布時間:2021-05-07 16:36:21 來源:億速云 閱讀:117 作者:Leah 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關使用Django框架怎么實現(xiàn)首頁和登錄頁分離,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

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設置

使用Django框架怎么實現(xiàn)首頁和登錄頁分離

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

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

3.在login方法下響應login模板和完成登錄功能

def login(request):
  msg = {'result': ''}
  if request.method == 'POST':
    getUserName = request.POST.get('username')
    getPwd = request.POST.get('pwd')
    # 實例化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'] = '用戶名或密碼錯誤'
  myReponse = render_to_response("login.html", msg)
  return myReponse

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

UserClass.py:

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

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

from UserClass import UserLogin

表示從UserClass中導入UserLogin。

4.在login方法中,登錄成功就跳轉到了首頁,首頁顯示登錄用戶名

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首頁</title>
</head>
<body>
  <h3>這是首頁,當前登錄用戶是:{{ username }}</h3>
  <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

關于使用Django框架怎么實現(xiàn)首頁和登錄頁分離就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI