Suppose the name of my Django project is 'django_project' which contains an app named 'main', and I have created a directory called 'utilities_dir' that contains a few python files (like 'utility_1.py', 'utility_2.py' et-cetera) having the functions I want to use. Where do I place the 'utilities_dir' and how do I use those files in, say, my 'views.py' file in the 'main' app directory? Thanks!
Asked
Active
Viewed 2,860 times
2 Answers
4
Place utilities dir in your project root folder, add __init__.py
file to the folder then when you want use your utilities function, just do that:
from utilities_dir.utility_1 import *
from utilities_dir.utility_2 import a_specific_function
Structure
- django_project
- main
- views.py
- utilities_dir
- __init__.py
- utility_1.py
- utility_2.py

levi
- 22,001
- 7
- 73
- 74
-
I'm sorry, but do you want me to place that in the 'django_project' folder parallel with the 'main' app folder? – Vikrant Aug 12 '14 at 04:59
-
@vik yes, just create an empty file called `__init__.py` and place it inside your utilities dir. – levi Aug 12 '14 at 05:01
-
@vik np :) here you can read about what exactly init.py file does: http://stackoverflow.com/questions/448271/what-is-init-py-for – levi Aug 12 '14 at 05:06
1
If I understand your question correctly you want to import some files from a folder located within your django project. If the following is your directory structure
- django_project
- main
- views.py
- utilities_dir
- __init__.py
- utility_1.py
- utility_2.py
You simply need to do this in your views.py
from utilies_dir import utility_1, utility_2
and then use the functions with utility_1.some_function()
, utility_2.some_function()
.

Archit Verma
- 1,911
- 5
- 28
- 46
-
1Unfortunately, that doesn't work. When I run it on my browser, I receive a message saying no such module ('utilities_dir') was found. – Vikrant Aug 12 '14 at 04:57
-
-
@levi I don't think so, I have a project with same structure without any `init.py` file and it works perfectly fine. – Archit Verma Aug 12 '14 at 05:01
-
-
@ArchitVerma that error its because Python can find that module because you need add init.py file. – levi Aug 12 '14 at 05:04
-
1
-
@levi My bad. You are right. You need to add a `__init.py__` file. – Archit Verma Aug 12 '14 at 05:11