the flash the flash - 6 months ago 11
Python Question

not able to import a file from an app to another

I have a django project with srtucture like this:

main_project

----main_project

<------libs

<<---------exceptions.py

----project_a

----project_b

In the views.py of project_a I am trying to import a folder named libs of main_project and a file from libs called exceptions.py, but I am getting the error

ImportError: No module named libs.exceptions


My code is :

from main_project.libs.exceptions import (
APIException400,
APIException405,
APIException403,
exception_handler_dispatcher,
)


Can someone tell me what am I missing here?
With reference to http://stackoverflow.com/a/31407131/5080347 answer I even tried :

from main_project.main_project.libs.exceptions import (
APIException400,
APIException405,
APIException403,
exception_handler_dispatcher,
)


but doesn't work.

Answer

It seems like you forgot to add __init__.py to libs directory.

The __init__.py is used to initialize Python packages. Check the documentation to better understand how things are working.

Your structure should looks as follow:

    project/
    |   
    |-- __init__.py
    |   
    |-- module_a/
    |   |-- __init__.py
    |   |
    |   |-- file1.py
    |   |
    |   |-- file2.py
    |
    |-- module_b/
    |   |
    |   |-- __init__.py
    |   |
    |   |-- file1.py
    |   |
    |   |-- submodule/
    |   |   |--__init__.py
    |   |   |
    |   |   |-- file1.py