【问题标题】:DJANGO_SETTINGS_MODULE not defined when building Sphinx documentation构建 Sphinx 文档时未定义 DJANGO_SETTINGS_MODULE
【发布时间】:2016-03-25 21:44:08
【问题描述】:

我正在关注 this tutorial 以便为我的 Django 项目生成文档。

我已将sys.path.append(os.path.join(os.path.dirname(__name__), '..')) 添加到我的文档目录中的conf.py 文件中。

但是运行make html 总是给我这样的错误:

ImproperlyConfigured:请求设置 LOGGING_CONFIG,但未配置设置。您必须在访问设置之前定义环境变量 DJANGO_SETTINGS_MODULE 或调用 settings.configure()。

我的项目运行良好,所以我不确定应该在哪里打电话给settings.configure()

【问题讨论】:

    标签: python django python-sphinx


    【解决方案1】:

    目录结构

    基于具有以下目录结构的 vanilla 安装,这里是应该工作的步骤。只要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 和解析 .rst 文件中的 autodoc 指令所必需的。

    2 ⇒ 使用设置模块的位置设置环境变量。此示例基于 vanilla django-admin 设置。如果您使用更复杂的设置结构(例如,devstagingproduction 设置从一些基本设置扩展而来)只需更新路径,例如myproj.settings.dev.

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

    现在应该为$ make htmlautodoc 合作准备就绪。

    【讨论】:

    • 啊...对我的conf.py 进行了这些更改,并将我的 docs 文件夹移到了 myproject 之外,现在它可以工作了!谢谢!
    猜你喜欢
    • 2011-07-16
    • 2015-03-15
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多