I have the following folder structure
app/ app/helpers/ app/helpers/methodhelper.py app/methods/ app/methods/method.py
and I'm trying to import a function from methodhelper.py inside method.py
so I tried the following:
import app.helpers.methodhelper OR from app.helpers.methodhelper import function1 OR import helpers.methodhelper
and I get:
"No module named app.helpers.methodhelper"
Important to note: helpers/__init__.py
already exists
How should this be done ?
If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.
Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole way. The import statement consists of the import keyword alongside the name of the module.
Your Django project's default path is in the root directory of the project (where the manage.py file is). You can either add the sub directories below that to your PYTHONPATH (easily done by appending to sys.path) or you can import that function using the full module path:
from projectname.app.helpers.methodhelper import function1
When I start a Django project, I always add
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
to my settings.py
. This path looks similar to /home/kyle/django_project_name/
. Inside that directly is manage.py
.
From there, also in my settings.py
, I include:
sys.path.append(os.path.join(PROJECT_ROOT, 'django_project_name'))
This makes my apps importable without the need to include my project name in the module path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With