Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sphinx - Documenting Django models

I'm using Sphinx in order to document a Django application I have.

When auto-generating documents I would like Sphinx to add the fields of each module within the documentation.

Sphinx totally skips these. In fact there is no trace of the fields whatsoever.

Any ideas?

like image 730
RadiantHex Avatar asked Oct 16 '12 10:10

RadiantHex


2 Answers

You have to use

@param description

in the model's docstring, for each field you want to be documented by sphinx.

Or in alternative, you should take a look at this snippet that does what you want (minus the boring writing part)

[EDIT]

If you plan to use this snippet, in django>=1.6

obj._meta._fields() 

has been removed please change it to

_meta.fields 
like image 156
Samuele Mattiuzzo Avatar answered Jan 01 '23 20:01

Samuele Mattiuzzo


Here is a snippet mentioned by @Samuele Mattiuzzo above, updated to support actual Django versions (tested on 1.11 LTS):

import inspect
from django.utils.html import strip_tags

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(field.help_text)

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = field.verbose_name

            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))

            # 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)

Just add it to the end of your conf.py and model fields will be added automatically to documentation.

like image 31
Igor Pomaranskiy Avatar answered Jan 01 '23 20:01

Igor Pomaranskiy