Django Session variables not visible after login [duplicate]
I am developing a hospital site. patients are allowed to login and book appointment. When a patient logs in, a sessions is initiated and saved. Again, I debugged, by adding a print statement after saving the sessions in the login view and its good, but when i try to book an appointment, then i print the session variables, they are empty. Could anyone please help me on this.... I would really appreciate.
Note: My frontend is built with Next.js and am adding credentials='include'
on my request. Also the cookies are set well in my browser with the key: sessionid and its value.
const response = await fetch(
"http://127.0.0.1:8000/bookings/book-appointment/",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(appointmentData),
credentials: "include"
}
);
@csrf_exempt
def login_view(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
email = data.get('email')
password = data.get('password')
# Fetch the user from the database
user = Patient.objects.filter(email=email).first()
# Check if user exists and password is correct
if user and user.check_password(password):
# Handle 2FA if enabled
if user.enable_2fa:
generate_and_send_2fa_code(user)
return JsonResponse({
'success': True,
'message': '2FA code sent',
'user_id': user.id,
'email': user.email,
'requires_2fa': True
})
# Set session expiry time
request.session.set_expiry(2 * 60 * 60) # 2 hours
# Log the user in and save the session
login(request, user)
# Set a cookie for the session ID
response = JsonResponse({
'success': True,
'message': 'Login successful. Welcome!',
'user_id': user.id,
'email': user.email,
'session_id': request.session.session_key
})
response.set_cookie(
key='sessionid',
value=request.session.session_key,
max_age=2 * 60 * 60,
)
request.session.save()
print("Login Session data:", request.session.items())
print("Login Session ID:", request.session.session_key)
return response
else:
return JsonResponse({'success': False, 'message': 'Invalid credentials'})
except Exception as e:
return JsonResponse({'success': False, 'message': f'An error occurred: {str(e)}'})
return JsonResponse({'success': False, 'message': 'Invalid request method'})
@csrf_exempt
def book_appointment(request):
if request.method == 'POST':
# Debugging: Print session data and session ID
print("Session data:", request.session.items())
print("Session ID:", request.session.session_key)
request.session.modified = True # Here
try:
data = json.loads(request.body)
# Extract data from the session
user_id = request.session.get('user_id')
patient_email = request.session.get('email')
if not user_id or not patient_email:
return JsonResponse({'status': 'error', 'message': 'User not authenticated'}, status=401)
# Extract other data from the request
doctor_name = data.get('doctorName')
speciality = data.get('speciality')
date = data.get('date')
time = data.get('time')
period = data.get('period')
consultation_type = data.get('consultationType')
problem_description = data.get('problemDescription')
patient_name = data.get('patientName') # Or use the patient's name from session
doctor_image = data.get('doctor_image')
# Check if the patient has already booked an appointment with the same doctor at the same time
existing_appointment = Appointment.objects.filter(
doctor_name=doctor_name,
date=date,
time=time,
patient_email=patient_email
).first()
if existing_appointment:
return JsonResponse({
'status': 'error',
'message': 'You already have an appointment with this doctor at this time.'
}, status=400)
# Check if the doctor is already booked for that time
doctor_appointment = Appointment.objects.filter(
doctor_name=doctor_name,
date=date,
time=time
).exists()
if doctor_appointment:
return JsonResponse({
'status': 'error',
'message': 'The doctor is not available at this time. Please choose another time slot.'
}, status=400)
# Save the new appointment to the database
appointment = Appointment.objects.create(
doctor_name=doctor_name,
speciality=speciality,
date=date,
time=time,
period=period,
consultation_type=consultation_type,
problem_description=problem_description,
patient_name=patient_name, # You might also use a session-stored patient name
patient_email=patient_email,
doctor_image=doctor_image
)
return JsonResponse({
'status': 'success',
'appointment_id': appointment.id,
'message': 'You have successfully booked an appointment!'
})
except json.JSONDecodeError:
return JsonResponse({'status': 'error', 'message': 'Invalid JSON'}, status=400)
return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)
And this is my settings as well
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000',
'http://127.0.0.1:3000',
]
CORS_ALLOW_CREDENTIALS = True
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'patients',
'rest_framework',
'corsheaders',
'authentication',
'allauth',
'bookAppointments',
'timelines',
'chats',
'doctorsnotes',
'medication',
'noticeboard',
'online_doctors',
]
AUTH_USER_MODEL = 'authentication.User'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_SAVE_EVERY_REQUEST = True
MIDDLEWARE = [
'patients.middleware.DisableCSRF',
'corsheaders.middleware.CorsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]