如何将Django设置导入到Python独立脚本 [英] How to import Django Settings to python standalone script
问题描述
我在调用django脚本时遇到困难.这是我当前在根目录中执行的操作:
I'm having difficulty calling a django script. Here is what I'm currently doing in my root directory:
>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py'
>>> from django.conf import settings
>>> settings.configure()
>>> settings.DATABASES
{}
settings.DATABASES
不应为空,所以我知道我没有正确初始化项目.我将如何在django2.1中做到这一点?我以前可以使用 import设置轻松地做到这一点;setup_environ(settings)
,但现在不行了.
The settings.DATABASES
should not be empty, so I know I haven't initialized the project correct. How would I do this in django2.1? I used to be able to do this easily using import settings; setup_environ(settings)
, but not anymore.
注意:我希望能够从任何目录运行以上命令.这是一个尝试从 tmp
导入我的项目的示例:
Note: I'm looking to be able to run the above from any directory. Here is an example from trying to import my project from tmp
:
(V) david$ cd /tmp && python
>>> import django
>>> from django.conf import settings
>>> settings.configure()
>>> django.setup()
>>> from users.models import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'users'
推荐答案
2.1文档指出您现在需要使用 setup()
.相关代码段:
The 2.1 docs state that you need to use setup()
now. Relevant snippet:
import django
from django.conf import settings
settings.configure()
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from myapp import models