简体   繁体   中英

Django Cannot Import File in Subdirectory

I'm almost certain I'm missing something obvious, but imports have plagued me for a while.

I have the following app structure in a larger Django project:

\reporting\
\reporting\__init__.py
\reporting\<all other default django files>
\reporting\utils\__init__.py
\reporting\utils\base_file.py
\reporting\utils\appname_reporting.py

I am trying to import appname_reporting to my \\reporting\\views.py .

I have tried import utils.appname_reporting , from utils import appname_reporting , and from .utils import appname_reporting . All of them give me an error: ImportError: No module named 'appname_reporting' .

There are no other files importing appname_reporting.py . And appname_reporting.py imports base_file.py .

Update

I got the appname_reporting to import in the views.py , but now I have a broken import in appname_reporting saying it can't import base_file . In there I simply have import base_file , and it it fails in my tests. I also tried import .base_file and it fails.

You need to have /reporting in your PYTHONPATH environment variable. Check that it is included in the output of

import sys
for p in sys.path: 
    print p

After that you can use relative imports:

appname_reporting.py:
from . import base_file

views.py
from .utils import appname_reporting

Watch out for circular imports however (eg if you're importing something in the __init__.py files).

You can run Python with the verbose switch:

python -v views.py

to see what is being imported, and in which order. It will tell you if you have a circular import.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM