def check_login(func): # 自定義登陸驗證裝飾器 def warpper(request, *args, **kwargs): is_login = request.session.get('is_login', False) if is_login: func(request, *args, **kwargs) else: return redirect("/login") return warpper
def login_user(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): all_data = form.clean() #獲取post數據,例如 {'username': u'yang1', 'password': 111} exist = User.objects.filter(username = all_data['Form_username'],password = all_data['Form_password']).first() if exist: request.session['is_login'] = True #設置session的隨機字段值 request.session['username'] = exist.username #設置uname字段爲登陸用戶 return redirect('/home') else: return HttpResponse("帳戶或密碼錯誤") else: form = LoginForm() return render(request, 'login.html', {'form': form}) @Check_Login def home(request): username = request.session.get('uname', False) #獲取登陸用戶名 return render(request, home.html', {'username': username}) #用戶名渲染到前端頁面