I have a React JS – Django site and I implemented the login functionality. But I have seen that the user does not stay logged in even though it authenticates and moves to the home page after log in. I tried displaying the username once it navigates to the home page and it returns empty.
Views.py
class Login(APIView):
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
# Authenticate user
user = authenticate(request, username=username, password=password)
if user is not None:
# If authentication succeeds, log in the user
login(request, user)
return JsonResponse({"message": "Login successful"})
else:
# If authentication fails, return error response
return JsonResponse({"error": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST)
Login.js
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch("http://localhost:8000/login/", {
method: 'POST',
withCredentials: true,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (response.ok && data.message === "Login successful") {
// Redirect to the home page upon successful login
navigate('/');
} else {
// Set error state with the error message
setError(data.error);
}
} catch (error) {
// Handle network or server errors
setError("An error occurred during login. Please try again later.");
}
I have the necessary session middleware in my settings.py as well.
I tried adding middleware to settings.py and session cookie age but it didnt work either