Reputation: 24131
Suppose I have the following Django project:
/ # Project dir
/myapp # App dir
/myapp/views.py # views file
/myapp/mymodule.py # a Python module
/myapp/management/commands/mycommand.py # command file
In the views file, I can import mymodule.py
by simply writing import mymodule
in views.py
. However, if I do the same in mycommand.py
, I get the error: ImportError: no module named mymodule
. I know that to import a model, I can write from myapp.models import mymodel
, but mymodule
is not a model, it is a separate Python module. So, how do I import this moduel into my command file?
Upvotes: 0
Views: 138
Reputation: 3503
The fact that you are unable to do this means your myapp folder is not in the python's sys.path
. The reason it worked in views.py
is because mymodule.py
is in the current directory of views.py
Assuming your Project dir (/) is in the python's sys.path
:
__init__.py
in myapp directory. This file can be blank.import myapp.mymodule
or from myapp import mymodule
The same logic applies for n levels deep. If you have myapp/myappdir1/myappdir2/myfile.py
you can do import myapp.myappdir1.myappdir2.myfile
assuming each of these have __init__.py
file in them.
Check https://docs.python.org/2/tutorial/modules.html#the-module-search-path for python's module search path
Upvotes: 0
Reputation: 5588
Thats because of where mymodule is in relation to all of your other files.
If you type
from myapp import mymodule
In mycommand.py as long as you have set up your __init__.py
files correctly in myapp and are using a setup.py file you should be fine. The modules documentation has more information on this
Upvotes: 2