I'm using Django and React to create a login page. When the user clicks on the submit button, I send an Axios POST request to my Django server to authenticate and login. In the login function, printing request.user works as intended. But as soon as the scope of the function is left, printing request.user prints AnonymousUser. I've talked to some people about it and they seem to think it's because cookies aren't persisting, but we haven't been able to solve the problem. Any guidance would be appreciated.
// 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")