Sphinx-apidoc на django build html failure на 'django.core.exceptions.AppRegistryNotReady'

Вопрос:

Я хочу писать документы с помощью sphinx в своем проекте django и автоматически создавать документы с комментариями кодов джанго.

Теперь у меня есть проект django (1.9), структура файла следующая:

myproject/
  myproject/
    __init__.py
    settings.py
    urls.py
    wsgi.py
  myapp/
    migrations/
    __init__.py
    admin.py
    models.py
    tests.py
    views.py
  docs/
    _build/
    _static/
    _templates/
    conf.py
    index.rst
    Makefile

Затем, как вы видите, я помещаю папку docs которой внутри находится проект dns Sphinx.

Теперь я могу редактировать *.rst файлы и build html.

Но когда я попытался autodoc содержимое, он терпит неудачу.

Вот что я сделал:

Во-первых, я добавил их в docs/conf.py, ref: qaru.site/info/5699740/...:

# 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.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

Затем я сделал действие sphinx-apidoc:

sphinx-apidoc -o docs/documentation .

После этого в docs/documentations я получил некоторые .rst файлы:

myproject/
  docs/
    documentations/
      myapp.rst
      myapp.migrations.rst
      myproject.rst
      manage.rst
      modules.rst

После этого я запускаю make html и получаю waring с:

sphinx-build -b html -d _build/doctrees   . _build/html
Running Sphinx v1.3.3
loading translations [zh_CN]... done
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 3 source files that are out of date
updating environment: 2 added, 3 changed, 0 removed
reading sources... [100%] documentation/modules                                 
/home/alfred/app/myproject/docs/documentation/core.rst:25: WARNING: autodoc: failed to import module 'core.models'; the following exception was raised:
Traceback (most recent call last):
  File "/home/alfred/.local/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 385, in import_object
    __import__(self.modname)
  File "/home/alfred/app/myproject/myapp/models.py", line 4, in <module>
    from django.contrib.auth.models import User, Group
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/alfred/.local/lib/python3.5/site-packages/django/db/models/base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

/home/alfred/app/myproject/docs/documentation/core.migrations.rst:10: WARNING: autodoc: failed to import module 'core.migrations.0001_initial'; the following exception was raised:
Traceback (most recent call last):
  File "/home/alfred/.local/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 385, in import_object
    __import__(self.modname)
  File "/home/alfred/app/myproject/myapp/migrations/0001_initial.py", line 7, in <module>
    import django.contrib.auth.models
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/alfred/.local/lib/python3.5/site-packages/django/db/models/base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
/home/alfred/app/myproject/docs/documentation/myproject.rst:10: WARNING: invalid signature for automodule ('myproject.settings-sample')
/home/alfred/app/myproject/docs/documentation/myproject.rst:10: WARNING: don't know which module to import for autodocumenting 'myproject.settings-sample' (try placing a "module" or "currentmodule" directive in the document, or giving an explicit module name)
/home/alfred/app/myproject/docs/documentation/myproject.rst:26: WARNING: autodoc: failed to import module 'myproject.urls'; the following exception was raised:
Traceback (most recent call last):
  File "/home/alfred/.local/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 385, in import_object
    __import__(self.modname)
  File "/home/alfred/app/myproject/myproject/urls.py", line 20, in <module>
    url(r'^admin/', include(admin.site.urls)),
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 303, in urls
    return self.get_urls(), 'admin', self.name
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 258, in get_urls
    from django.contrib.contenttypes import views as contenttype_views
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/contenttypes/views.py", line 5, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/home/alfred/.local/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 159, in <module>
    class ContentType(models.Model):
  File "/home/alfred/.local/lib/python3.5/site-packages/django/db/models/base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "/home/alfred/.local/lib/python3.5/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
looking for now-outdated files... none found
pickling environment... done
checking consistency... /home/alfred/app/myproject/docs/documentation/modules.rst:: WARNING: document isn't included in any toctree
done
preparing documents... done
writing output... [100%] index                                                  
generating indices... genindex py-modindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded, 6 warnings.

Build finished. The HTML pages are in _build/html.

Что я сделал не так? Как я могу создать документ с кодом django?

Ответы

Ответ 1

Долгое время найти решение:

В conf.py добавьте следующее:

import django
sys.path.insert(0, os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()