Answer the question
In order to leave comments, you need to log in
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()
os.chdir()
, then the "launcher" works fine. 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
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.path
path 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 questionAsk a Question
731 491 924 answers to any question