我在调用 Django 脚本时遇到困难。这是我目前在我的根目录中所做的:
>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py'
>>> from django.conf import settings
>>> settings.configure()
>>> settings.DATABASES
{}
settings.DATABASES
不应为空,因此我知道我没有正确初始化项目。我将如何在 django2.1 中执行此操作?我曾经能够使用 import settings 轻松地做到这一点; setup_environ(settings)
,但现在不是了。
注意:我希望能够从任何目录运行上面的代码。这是一个尝试从 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()
。相关片段:
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
Here is the full documentation.
我是一名优秀的程序员,十分优秀!