django自定義用戶表實現登入後才能訪問相關界面(未繼承自帶用戶表)

在apps文件下建立.py文件(建議)你想放哪裏都行。

from django.http import HttpResponseRedirect

#全局訪問控制函數
def login_required(func):
    def check_login(request):
        if request.session.has_key('username'):
            # 當前有用戶登錄,正常跳轉
            return func(request)
        else:
            # 當前沒有用戶登錄,跳轉到登錄頁面
            return HttpResponseRedirect('/login')
    return check_login

導入到視圖文件中,視圖類中這樣寫:

from ..globleuse import login_required
from django.utils.decorators import method_decorator


class Index(View):
    @method_decorator(login_required)
    def get(self, request):
        return render(request, 'index.html', {})

    def post(self, request):
        pass

ko, be crowned with success.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章