Reputation: 121
ı have a django project and i need to access some of models in my folder that under the django main project folder.Let me illustrate this.
src\
main\
urls.py
models.py
view.py
lib\
__init__.py
helper.py
This is the example folder structure and i need to import some class of main app's models inside the helper.py.I tried these:
from main.models import exampleClass
from ..main.models import exampleClass
And i also tried adding a __init__.py
file in the main project folder:
src\
...
main\
lib\
__init__.py
Always errors 2 kind :
1)ValueError : relative import error 2) no module name..
I need the solution and need good explanation why i failed always.Thank you so much guys.
Upvotes: 0
Views: 346
Reputation: 3729
How did you set $PYTHONPATH variable ? The search paths are relative to this environment variable.
So if you want to specify a path like main.models
, it should contain the src
directory.
Note that you can also manage it with the sys.path
array.
Django normally add all the applications to sys.path
. You may try to print it inside the settings.py
file to have an idea.
To add a path from the settings.py file of the project, you could do something like:
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR, "../lib"))
If for example you have a lib
directory at the same level as the directory that contains the settings.py
file.
Upvotes: 0
Reputation: 10256
You don't need ..
if main
and lib
are both django's apps, and you have registered them in INSTALLED_APPS
settings.
If main
and lib
are in the same level that manage.py
:
src/
main/
...
lib/
...
manage.py
...
You just need:
from main.models import exampleClass
Upvotes: 0
Reputation: 48090
Add __init__.py
in main
folder instead of src
folder. Then try to import using from main.models import exampleClass
. It should be working.
Upvotes: 1