Sashaank
Sashaank

Reputation: 964

How to import file from a nested directory with django

I am building a django web application. For the code, I have a few helper functions I am trying to import, but django gives me a ModuleNotFoundError. This is my file structure

── stock_predictor
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── models_helper
    │   ├── __init__.py
    │   ├── arma.py
    │   ├── data_handler.py
    │   └── yahoo_stock_data.py
    ├── tasks.py
    ├── templates
    │   ├── base.html
    │   └── homepage.html
    ├── tests.py
    ├── urls.py
    └── views.py

Here the models_helper directory contains a list of files I want to import in the tasks.py file. I tried adding the __init__.py file to the models_helper directory, but this does not solve the issue. I also tried adding the path to sys.path. That, too, does not seem to solve the problem. My imports in the tasks.py files are as follows.

from models_helper.yahoo_stock_data import YahooStockData
from models_helper.data_handler import DataHandler
from models_helper.arma import AlgoARMA

The error I get is as follows.

ModuleNotFoundError: No module named 'models_helper'

NOTE: This seems to be a django issue as I can import using sys and run the python script directly from the terminal.

These are the links I followed to get the code to work, but it does not.

  1. Importing modules from nested folder
  2. Import a module from a relative path
  3. Importing files from different folder

Upvotes: 1

Views: 1534

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

Normally the root is the directory just above the apps, so you import with the name of the app as first module name:

from stock_predictor.models_helper.yahoo_stock_data import YahooStockData

in modules in the application (stock_predictor), like for example models.py, views.py, tasks.py, etc. you can use a relative import like:

# for models.py, views.py, tasks.py, etc.

from .models_helper.yahoo_stock_data import YahooStockData

Upvotes: 1

VipulVyas
VipulVyas

Reputation: 71

You want to add import in task.py then it should like

relative import

from models_helper import YahooStockData
from models_helper import DataHandler
from models_helper import AlgoARMA

because init.py shows that this is a package folder, you have to import from that package, here models_helper is a package, and YahooStockData is your import.

absolute import

import models_helper.yahoo_stock_data 
import models_helper.data_handler
import models_helper.arma

Import from root

from stock_predictor.models_helper.yahoo_stock_data import YahooStockData
from stock_predictor.models_helper.data_handler import DataHandler
from stock_predictor.models_helper.arma import AlgoARMA

Upvotes: 0

Related Questions