当我开始使用 Django 时,这个问题一直困扰着我。假设您有一个project
带有 app 的项目app
,并且您想要检查它。因此,您可以在 Python shell 中导入它的一部分:
(virtualenv) $ PYTHONPATH=. python
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import project.app.views
(...cut traceback...)
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS,
but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE
or call settings.configure() before accessing settings.
美好的。所以你设置DJANGO_SETTINGS_MODULE
:
(virtualenv) $ PYTHONPATH=. DJANGO_SETTINGS_MODULE=project.project.settings python
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import project.app.views
(...cut traceback...)
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
没有解释下一步该做什么。
答案1
答案是:
- 设置
DJANGO_SETTINGS_MODULE
为project.project.settings
(其中project
是您的项目名称) - 在 Python shell 中,
import django; django.setup()
这是您要做的第一件事。
因此,例如:
(virtualenv) $ PYTHONPATH=. DJANGO_SETTINGS_MODULE=project.project.settings python
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django; django.setup()
>>> import project.app.views
都好!