Django 實現登錄后跳轉


說明

實現網頁登錄后跳轉應該分為兩類:即登錄成功后跳轉登錄失敗再次登錄成功后跳轉。參考網上內容,基本都只實現了第一類。而沒有實現第二類。

實現

為了能讓登錄失敗后再次登錄成功后還能實現跳轉。我這里采用了笨辦法, 即:無論登錄成功與否,都將跳轉鏈接在前后端進行傳遞 ,這樣跳轉鏈接就不會在登錄失敗后消失。不多說,上代碼

后端 views.py

from django.shortcuts import render, redirect

def login(request):
    # 當前端點擊登錄按鈕時,提交數據到后端,進入該POST方法
    if request.method == "POST":
        # 獲取用戶名和密碼
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        # 在前端傳回時也將跳轉鏈接傳回來
        next_url = request.POST.get("next_url")

        # 對用戶進行驗證,假設正確的用戶名密碼為"aaa", "123"
        if username == 'aaa' and passwd == '123':
            # 判斷用戶一開始是不是從login頁面進入的
            # 如果跳轉鏈接不為空並且跳轉頁面不是登出頁面,則登錄成功后跳轉,否則直接進入主頁
            if next_url and next_url != "/logout/":
                response = redirect(next_url)
            else:
                response = redirect("/index/")
            return response
        # 若用戶名或密碼失敗,則將提示語與跳轉鏈接繼續傳遞到前端
        else:
            error_msg = "用戶名或密碼不正確,請重新嘗試"
            return render(request, "app/login.html", {
                'login_error_msg': error_msg,
                'next_url': next_url,
            })
    # 若沒有進入post方法,則說明是用戶剛進入到登錄頁面。用戶訪問鏈接形如下面這樣:
    # http://host:port/login/?next=/next_url/
    # 拿到跳轉鏈接
    next_url = request.GET.get("next", '')

    # 直接將跳轉鏈接也傳遞到后端
    return render(request, "autotest/login.html", {
        'next_url': next_url,
    })

前端頁面 login.html

   <form action="{% url 'login' %}" method="post">
                 <h1>請使用xxx登錄</h1>
                 <div>
                   <input id="user" type="text" class="form-control" name="username" placeholder="賬戶" required="" />
                 </div>
                 <div>
                   <input id="pwd" type="password" class="form-control" name="password" placeholder="密碼" required="" />
                 </div>
       // 注意這里多了一個input。它用來保存跳轉鏈接,以便每次點擊登錄按鈕時將跳轉鏈接傳遞回后端
       // 通過display:none屬性將該input元素隱藏起來
                   <div style="display: none;">
                       <input id="next" type="text" name="next_url" value="{{ next_url }}" />
                   </div>
       // 判斷是否有錯誤提示,若有則顯示
                   {% if login_error_msg %}
                       <div id="error-msg">
                           <span style="color: rgba(255,53,49,0.8); font-family: cursive;">{{ login_error_msg }}</span>
                       </div>
                   {% endif %}
                 <div>
                     <button type="submit" class="btn btn-default" style="float: initial; margin-right: 60px">登錄</button>
                 </div>
   </form>

總結

其實這種實現方式就是讓跳轉鏈接在前后端交互中不損失掉。當然也可以在前端不用form元素,直接用ajax的post形式,然后讓跳轉在前端的ajax邏輯中執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM