构建Sphinx文档时未定义DJANGO_SETTINGS_MODULE

tha*_*ksd 2 python django python-sphinx

我正在学习本教程,以便为我的Django项目生成文档.

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

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

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

我的项目运行正常,所以我不确定我应该打电话到settings.configure()哪里?

sth*_*hzg 8

目录结构

基于具有以下目录结构的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
Run Code Online (Sandbox Code Playgroud)

Sphinx配置

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
Run Code Online (Sandbox Code Playgroud)

1⇒将Django项目目录(带有manage.py)附加到Python路径,这对于2和解析文件中的autodoc指令是必需的.rst.

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

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

现在一切都应该到位,$ make html以便与之合作autodoc.