Django首頁顯示用戶名


Django首頁顯示用戶名

實現效果圖:

編寫前端頁面:

<tr v-if="username">
    <td>當前登錄用戶:[[username]]</td>
    <td><a href="/logout/">注銷</a></td>
</tr>
<tr v-else="username">
    <td><a href="/login/">登錄</a></td>
    <td><a href="/register/">注冊</a></td>
</tr>

vue中需要綁定的變量:[[ username ]]

實現原理:

用戶登錄之后,保持登錄狀態,隨后在cookie中添加登錄信息。

頁面重定向到首頁時,vue讀取cookie。若cookie有用戶名信息,則顯示已登錄狀態,若沒有,則顯示未登錄狀態。

配置路由:

from django.conf.urls import url
from . import views

urlpatterns = [
    url('^$', views.IndexView.as_view()),
]

編寫視圖函數:

from django.shortcuts import render
from django.views import View

class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')

獲取cookie的js函數:

// 獲取cokie
function getCookie(name){
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

Vue:

var vm = new Vue({
    el:'#app',
    delimiters:['[[', ']]'],
    data:{
        host, 
        username:''
    },
    mounted(){
        this.username = getCookie('username');
        console.log(this.username);
    },
    methods:{}
});

在登錄及注冊視圖函數中設置cookie:

# 登錄狀態保持
login(request, user)

# 響應
response = redirect('/')
response.set_cookie('username', user.username, max_age=60 * 60 * 24 * 14)
return response

源碼


免責聲明!

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



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