python - Django登录状态没有保存
问题描述
我正在使用 Django 和 React 创建登录页面。当用户单击提交按钮时,我向我的 Django 服务器发送一个请求Axios
POST
到. 在登录功能中,打印按预期工作。但是一旦离开函数的范围,打印就会打印. 我和一些人谈过这件事,他们似乎认为这是因为 cookie 没有持久化,但我们无法解决问题。任何指导将不胜感激。authenticate
login
request.user
request.user
AnonymousUser
// REACT FORM
function submitHandler(event) {
event.preventDefault();
const state = login ? "login" : "signup";
axios
.post(`http://localhost:8000/auth/${state}`, {
username: username,
password: password,
})
.then((response) => {
setRedirectMessage(response.data);
axios
.post("http://localhost:8000/auth/user")
})
.catch((err) => alert(err.response.data));
}
# LOGIN REQUEST (/auth/login)
@require_POST
@csrf_exempt
def auth_login(request):
if request.user.is_authenticated:
return HttpResponseBadRequest("You are already logged in")
username, password = get_credentials(request)
user = authenticate(username=username, password=password)
if user is None:
return HttpResponseBadRequest("Those credentials do not exist")
login(request, user)
print(user) # PRINTS CORRECTLY
print(request.user) # PRINTS CORRECTLY
return HttpResponse("You have successfully logged in with username " + username)
# GET REQUEST TO CHECK LOGIN STATE (auth/user)
@csrf_exempt
def get_user(request):
print(request.user)
return HttpResponse("Hey there")
解决方案
推荐阅读
- python - 由于 jsonschema 无法编译 python 程序
- c# - C# DataGridView 选择模式:单元格选择 - 是否可以检索该选定行的特定列值?
- android - Flutter 天气应用中的城市选择 - Flutter
- mysql - 合并两张表,使用先进先出排序
- android - 为什么 Android App Links 的自动验证失败
- java - 如何过滤 2 个巨大的列表,其中包含数百万个具有相同 ID 的项目
- image - 如何调整图像大小 woocommerce oceanwp
- python - 安装 pyinstaller 的错误
- c# - 退出时的 Visual Studio Code 会杀死附加了 C# 调试器的外部 .exe 进程
- angular - 在 karma 中测试订阅会给出错误“Observable<>”类型的参数不能分配给“订阅”类型的参数