python - 构建 Sphinx 文档时未定义 DJANGO_SETTINGS_MODULE

标签 python django python-sphinx

我正在关注 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 设置。如果您正在使用更复杂的设置结构(例如 devstagingproduction 设置从一些基本设置扩展而来),只需更新路径,例如myproj.settings.dev

3 ⇒ 最后调用django.setup()是填充 Django 的应用程序注册表所必需的,Sphinx 需要它才能从完整的 Django 设置生成文档。

$ make htmlautodoc 一起工作的一切都应该就绪。

关于python - 构建 Sphinx 文档时未定义 DJANGO_SETTINGS_MODULE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228537/

相关文章:

python - Django get_or_create 在 ModelForm 的 clean 方法中不返回可用的 Model 对象

python - 在 mysql 中插入一个 python 列表

python - "Unrolling"递归函数?

python - 如何在OpenCV中区分实心圆/轮廓和未实心圆/轮廓?

django - DRF YASG 定制

python - 在 Django 中获取模型表单的保存对象?

latex - 如何为Latex/PDF输出添加图形/表格列表?

css - Sphinx 内联代码高亮

Django:将对象从模板传递到 View

python - Python-Sphinx 中的多级 Toctree