D
D
Dmitry2018-03-21 23:23:19
Django
Dmitry, 2018-03-21 23:23:19

How to run Django from another directory?

It is known that manage.py is located in the root folder of the Django project PRJ_ROOT/.
I want to make a "launcher" in one of the subfolders, for example in PRJ_ROOT/bin/.
I write a launcher:

import os
import django.conf

# Определяю папку "запускалки" и иду на уровень выше из bin в PRJ_ROOT
_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))

# Меняю рабочую директорию на корень PRJ_ROOT
os.chdir(_dir)

print _dir # Выводит PRJ_ROOT
print os.getcwd() # Выводит PRJ_ROOT

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()

And it gives an error that it cannot import the project.settings module!
If I put the "launcher" along with manage.py and remove it from it os.chdir(), then the "launcher" works fine.
And why from other folder does not work??? After all os.chdir(), it is installed correctly - to the root of the project, where is manage.py ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-03-22
@dimanjy

Thanks Paul, got it!
The problem was indeed in the paths that are deposited in sys.path. To run the Django console module from an arbitrary folder, you need to remove the sys.pathpath to this folder from the path and add the path to the root of the Django project:

import sys
import os
import django.conf

_curdir = os.path.abspath(os.path.dirname(__file__))        # Текущая директория
_newdir = os.path.abspath(os.path.join(_curdir, '../../../')) # Путь к корню Django-проекта

sys.path.remove(_curdir)     # Удаляем текущий путь
sys.path.insert(0, _newdir)  # Добавляем путь к корню

# Запускаем Django-окружение
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unit.settings')
django.setup()

# Дальше работаем с Django-моделями и делаем все, что нужно

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question