Having generated my first few real applications in Django, it became obvious there was at least one glaring omission to my development process – documentation!
I knew there were various solution to this problem, but after DjangoCon 2011 there was only one solution that seems to be talked about seriously – Sphinx.
Initial reading of the documentation and tutorials left me a little bewildered. However, after I managed to successfully setup and make my first html docs, it all seemed a little more straightforward. To help clarify this process for myself and anyone else in a similar situation, here are the steps I took.
Note: I am using Ubuntu linux. Process may differ for Mac/ Windows
- Install sphinx using
$ easy_install sphinx
- Navigate to your project directory and run
- Answer all questions. Importantly, answer yes to
autodoc: automatically insert docstrings from modules (y/N) [n]:
- This should produce a directory structure like so:
- Now we can run
$ make html
to create the first version of our docs. This will create the _build/html directory containing the html files
- Open index.html in the browser and you should see your empty (for the moment) project docs
- Now, to make use of the handy autodoc extension, we need to make sure conf.py is setup properly. First check that the autodoc extension is enabled:
# Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode']
Then edit the file to include the path and Django project settings:
# documentation root, use os.path.abspath to make it absolute, like shown here sys.path.insert(0, os.path.abspath('.')) # setup Django import settings from django.core.management import setup_environ setup_environ(settings)
- Now we can test this by referencing our first module. Create another directory called /modules in the project root and created models.rst to reference my models.py module in my app. In this write:
Models ======= .. automodule:: myapp.models :members:
- Now in index.rst we can add a reference to this module:
Contents: ========= .. toctree:: :maxdepth: 2 modules/models.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
- The autodoc extension should automatically extract information and comments about the models from models.
$ make html
again and refresh the docs in the browser. Now there should be section entitled models and page listing the classes, fields and comments of your models.py module
- From here you can explore some of the further options in autodoc such as:
Models: ====== .. automodule:: myapp.models :members: :undoc-members: :inherited-members:
Some useful links: