thanksd
thanksd

Reputation: 55644

DJANGO_SETTINGS_MODULE not defined when building Sphinx documentation

I'm following this tutorial in order to generate documentation for my Django project.

I've added sys.path.append(os.path.join(os.path.dirname(__name__), '..')) to the conf.py file within my documentation directory.

But running make html keeps giving me errors like this:

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.

My project is running fine, so I'm not sure where I'm supposed to call settings.configure()?

Upvotes: 4

Views: 1468

Answers (1)

sthzg
sthzg

Reputation: 5554

Directory Structure

Basing on a vanilla install with the following directory structure here are the steps that should work. The directory structure may be different as long as the path in conf.py is set correctly.

├── 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

Sphinx Configuration

conf.py needs a few settings so that autodoc is able to bootstrap the Django app:

# 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 ⇒ appending the Django project directory (the one with manage.py) to the Python path, which is necessary for 2 and for resolving autodoc directives in the .rst files.

2 ⇒ setting an env variable with the location of the settings module. This example is based on a vanilla django-admin setup. If you are using a more sophisticated settings structure (e.g. dev, staging, production settings extending from some base settings) just update the path, e.g. myproj.settings.dev.

3 ⇒ finally calling django.setup() is necessary to populate Django's application registry, which Sphinx needs in order to generate the docs from an intact Django setup.

Everything should be in place now for $ make html to work with autodoc.

Upvotes: 16

Related Questions