Skip to content

Instantly share code, notes, and snippets.

@sebastibe
Last active December 10, 2015 14:50
Show Gist options
  • Save sebastibe/4450508 to your computer and use it in GitHub Desktop.
Save sebastibe/4450508 to your computer and use it in GitHub Desktop.
Sphinx conf.py for the documentation of a Django project.
import sys
from os.path import abspath, join, dirname
DOC_ROOT = abspath(dirname(dirname(__file__)))
BASE_PATH = dirname(DOC_ROOT)
PROJECT_PATH = join(BASE_PATH, 'api')
sys.path.append(BASE_PATH)
sys.path.append(PROJECT_PATH)
from django.core.management import setup_environ
from projectname import settings
# Set up the Django settings/environment
setup_environ(settings)
sys.path.append(abspath(join(dirname(__file__), "_ext")))
extensions = ['sphinx.ext.autodoc',
'djangodocs']
import inspect
from os.path import abspath, join, dirname
from django.utils.html import strip_tags
from django.utils.encoding import force_unicode
def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta._fields()
for field in fields:
# Decode and strip any html out of the field's help text
help_text = strip_tags(force_unicode(field.help_text))
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = force_unicode(field.verbose_name).capitalize()
if help_text:
# Add the model field to the end of the docstring as a param
# using the help text as the description
lines.append(u':param %s: %s' % (field.attname, help_text))
else:
# Add the model field to the end of the docstring as a param
# using the verbose name as the description
lines.append(u':param %s: %s' % (field.attname, verbose_name))
if isinstance(field, models.ForeignKey):
to = field.rel.to
lines.append(u':type %s: %s to :class:`~%s.%s`' % (field.attname, type(field).__name__, to.__module__, to.__name__))
else:
# Add the field's type to the docstring
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
# Return the extended docstring
return lines
def setup(app):
# Register the docstring processor with sphinx
app.connect('autodoc-process-docstring', process_docstring)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment