Hey I’m new using django, I’m trying to store some information about the user in the session. I’m trying to store the values ‘user’, ‘role’ in the session but when accessing it the values aren’t stored I think I might be missing something can’t figure it out though. Im using
SESSION_ENGINE = ‘django.contrib.sessions.backends.db’
as the session engine. Any ideas?
@api_view(['POST'])
def check_user_exists(request):
user = request.data.get('user')
password = request.data.get('password')
if not user or not password:
return Response({"error": "Username and cedula are required."}, status=status.HTTP_400_BAD_REQUEST)
try:
userResponse = Usuarios.objects.get(usuario=user)
if check_password(password, userResponse.clave):
request.session['user'] = userResponse.usuario
request.session['role'] = userResponse.rol_id
print("Current session:", request.session.items())
return Response({'exists': True, 'message': f'User {user} authenticated.', 'rol': userResponse.rol_id}, status=status.HTTP_200_OK)
else:
return Response({'exists': False, 'message': 'Password incorrect.'}, status=status.HTTP_400_BAD_REQUEST)
except:
return Response({'exists': False, 'message': 'User not found.'}, status=status.HTTP_404_NOT_FOUND)
@api_view(['GET'])
def get_user_role(request):
role = request.session.get('role')
print("Current session:", request.session.items())
if role:
return Response({'status':'success', 'message': 'Role acquired', 'role': role})
else:
return Response({'status':'error', 'message':'User not logged in'})