Search code examples
pythondjangoglob

DJANGO : Can't list the content of a folder located in static directory in my django project


In my project I have a folder datasets in the static folder that content 2 others folders. I want to list the content of each of thosefolders and return it in HttpResponse. I define a utility function list_dir_content in utils/data.py where I use glob.glob() function by passing it paths of those folders but I recieve an empty result: an empty list [] from the glob.glob() function. How can I fix thet issue regardless of the os (I'm developping my internship project either on ubuntu or windows 10). Thanks! Here are the structure of my project and files views.py, models.py You can also see the code which call the utility function list_dir_content

#in views.py    
def server_uts_datasets(request):
    if request.method == 'GET':
        uts_datasets = Dataset.get_uts_datasets()
        uts_datasets_serializer = DatasetSerializer(uts_datasets, many=True)
        print(uts_datasets)
        return JsonResponse(uts_datasets_serializer.data, safe=False)

#in models.py
@classmethod    
def get_mts_datasets(cls): 
    mts_datasets_files = data.list_dir_content(settings.DATASETS_DIR)
    mts_datasets = []
    for mts_datasets_file in mts_datasets_files:
        dataset_type = 'mts'
        dataset_path = mts_datasets_file
        dataset_name = data.get_dataset_name(mts_datasets_file)
        dataset_nb_instances = data.get_nb_instances(mts_datasets_file)
        mts_dataset = Dataset(dataset_path = dataset_path, dataset_name = dataset_name, dataset_nb_instances = dataset_nb_instances, dataset_type = dataset_type)
        mts_datasets.append(mts_dataset)

    return mts_datasets



#in data.py
   import glob
   import os
   import pandas as pd
   import numpy as np
   import matplotlib.pyplot as plt

   def list_dir_content(dir_path, file_extension=''):
      files_pattern = dir_path + '/*.' + file_extension
      print("files_pattern : ", files_pattern)
     #files_results_paths = glob.glob(files_pattern)
     files_results_paths = glob.glob('../tsanalysisapp/static/tsanalysisapp/datasets/uts/*.')
     print("files_results_paths : ", files_results_paths)
     return files_results_paths

#in settings.py
MTS_DATASETS_DIR = os.path.join(BASE_DIR, 'tsanalysisapp/static/tsanalysisapp/datasets/mts') # paths to datasets in tne server
UTS_DATASETS_DIR = os.path.join(BASE_DIR, 'tsanalysisapp/static/tsanalysisapp/datasets/uts') # paths to datasets in tne server

Thanks in advance for your kindly help... structure of my django project


Solution

  • Just only replace in the os.path.join() function all the slashes / with ', ' that result in os.path.join('parent_dir_name', 'subdir_name', ..., 'last_dir_name', ''):

    MTS_DATASETS_DIR = os.path.join(BASE_DIR, 'tsanalysisapp', 'static', 'tsanalysisapp', 'datasets', 'mts', '*.')