'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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VipulVyas |
