Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django importing another file from another package

Tags:

python

django

I have the following folder structure

app/
app/helpers/
app/helpers/methodhelper.py
app/methods/
app/methods/method.py

and I'm trying to import a function from methodhelper.py inside method.py
so I tried the following:

import app.helpers.methodhelper
OR
from app.helpers.methodhelper import function1
OR
import helpers.methodhelper

and I get:

"No module named app.helpers.methodhelper" 

Important to note: helpers/__init__.py already exists

How should this be done ?

like image 966
Asaf Avatar asked May 13 '13 20:05

Asaf


People also ask

How do I import one py file to another?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.

How do you access a class from another file in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole way. The import statement consists of the import keyword alongside the name of the module.


1 Answers

Your Django project's default path is in the root directory of the project (where the manage.py file is). You can either add the sub directories below that to your PYTHONPATH (easily done by appending to sys.path) or you can import that function using the full module path:

from projectname.app.helpers.methodhelper import function1

When I start a Django project, I always add

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

to my settings.py. This path looks similar to /home/kyle/django_project_name/. Inside that directly is manage.py.

From there, also in my settings.py, I include:

sys.path.append(os.path.join(PROJECT_ROOT, 'django_project_name'))

This makes my apps importable without the need to include my project name in the module path.

like image 100
Kyle Avatar answered Oct 20 '22 19:10

Kyle