0

I work with Django Framework, and I try to open a Python file from outside the Django package. I use the OS library to get to the path that is outside the Django package, like this:

file_path = OS.path.join(settings.FILES_DIR, 'execute_get_symbols.py')

In file_path I got only the file path

I want to run a function that is inside the file "execute_get_symbols.py".

My questions are:

  • It is possible?
  • And if it is possible, so how.
  • And if it's not possible, So... how can I import files that are outside the Django package and execute the function? Like from package.file_name import function
Django
  • 45
  • 6

2 Answers2

1

You can imoprt your file by adding it to sys.path (the list of paths python looks at to import things) - i believe that this is a kinda hacky way but still commonly used by django users:

import sys
sys.path.append(path_to_your_file)
import your_file

Afterwards you should be able to use it normally

Chris
  • 379
  • 1
  • 2
  • 10
  • Hi, I tried the following code in the setting.py on Django MANAGE_DB = os.path.join(BASE_DIR.parent.parent, "manage_db") I made sure that this is indeed the desired address I made this import: from manage_db.execute_get_symbols import get_symbols and the error is: No module named 'manage_db.tools'; 'manage_db' is not a package – Django Dec 06 '22 at 12:54
0

I added the following code in settings file on Django:

sys.path.append(os.path.join(BASE_DIR.parent.parent, ""))  # To get the path from root until current directory 

And because of that, all the packages recognize on run time.

Django
  • 45
  • 6