我正在关注 this tutorial以便为我的 Django 项目生成文档。
我添加了 sys.path.append(os.path.join(os.path.dirname(__name__), '..'))
到 conf.py
我的文档目录中的文件。
但是运行 make html
总是给我这样的错误:
ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我的项目运行良好,所以我不确定应该在哪里调用 settings.configure()
?
最佳答案
目录结构
基于具有以下目录结构的原始安装,这里是应该起作用的步骤。只要conf.py
中的路径设置正确,目录结构可能会有所不同。
├── docs
│ ├── Makefile
│ ├── build
│ └── source
│ ├── _static
│ ├── _templates
│ ├── conf.py
│ └── index.rst
└── myproj
├── anapp
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── myproj
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
狮身人面像配置
conf.py
需要一些设置,以便 autodoc
能够引导 Django 应用程序:
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.join(os.path.abspath('.'), '../../myproj')) # <•• 1
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproj.settings' # <•• 2
import django
django.setup() # <•• 3
1 ⇒ 将 Django 项目目录(带有 manage.py
的目录)附加到 Python 路径,这是 2 和解析 autodoc< 所必需的
指令在 .rst
文件中。
2 ⇒ 使用设置模块的位置设置环境变量。此示例基于普通的 django-admin 设置。如果您正在使用更复杂的设置结构(例如 dev
、staging
、production
设置从一些基本设置扩展而来),只需更新路径,例如myproj.settings.dev
。
3 ⇒ 最后调用django.setup()
是填充 Django 的应用程序注册表所必需的,Sphinx 需要它才能从完整的 Django 设置生成文档。
$ make html
与 autodoc
一起工作的一切都应该就绪。
关于python - 构建 Sphinx 文档时未定义 DJANGO_SETTINGS_MODULE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228537/