在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.