Skip to content

Commit bdcf8ed

Browse files
authored
Merge pull request coddingtonbear#113 from ad-m/doc-field
Auto-add model fields as param in docs
2 parents 0e9f226 + 4ded1e1 commit bdcf8ed

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

docs/conf.py

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,5 +242,55 @@
242242
#texinfo_show_urls = 'footnote'
243243

244244
sys.path.insert(0, os.path.abspath('..'))
245+
import inspect
246+
import django
247+
from django.utils.html import strip_tags
248+
from django.utils.encoding import force_text
245249
from django.conf import settings
246-
settings.configure()
250+
settings.configure(INSTALLED_APPS=['django_mailbox', ])
251+
django.setup()
252+
253+
def process_docstring(app, what, name, obj, options, lines):
254+
# Source: https://gist.github.com/abulka/48b54ea4cbc7eb014308
255+
# This causes import errors if left outside the function
256+
from django.db import models
257+
258+
# Only look at objects that inherit from Django's base model class
259+
if inspect.isclass(obj) and issubclass(obj, models.Model):
260+
# Grab the field list from the meta class
261+
fields = obj._meta.get_fields()
262+
263+
for field in fields:
264+
# Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
265+
if not hasattr(field, 'verbose_name'):
266+
continue
267+
268+
# Decode and strip any html out of the field's help text
269+
help_text = strip_tags(force_text(field.help_text))
270+
271+
# Decode and capitalize the verbose name, for use if there isn't
272+
# any help text
273+
verbose_name = force_text(field.verbose_name).capitalize()
274+
275+
if help_text:
276+
# Add the model field to the end of the docstring as a param
277+
# using the help text as the description
278+
lines.append(u':param %s: %s' % (field.attname, help_text))
279+
else:
280+
# Add the model field to the end of the docstring as a param
281+
# using the verbose name as the description
282+
lines.append(u':param %s: %s' % (field.attname, verbose_name))
283+
284+
# Add the field's type to the docstring
285+
if isinstance(field, models.ForeignKey):
286+
to = field.rel.to
287+
lines.append(u':type %s: %s to :class:`~%s.%s`' % (field.attname, type(field).__name__, to.__module__, to.__name__))
288+
else:
289+
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
290+
291+
# Return the extended docstring
292+
return lines
293+
294+
def setup(app):
295+
# Register the docstring processor with sphinx
296+
app.connect('autodoc-process-docstring', process_docstring)

0 commit comments

Comments
 (0)