Skip to content

Instantly share code, notes, and snippets.

@abulka
Created March 21, 2016 07:25
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abulka/48b54ea4cbc7eb014308 to your computer and use it in GitHub Desktop.
Save abulka/48b54ea4cbc7eb014308 to your computer and use it in GitHub Desktop.
# Auto list fields from django models - from https://djangosnippets.org/snippets/2533/#c5977
import inspect
from django.utils.html import strip_tags
from django.utils.encoding import force_text
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.get_fields()
for field in fields:
# Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
if not hasattr(field, 'verbose_name'):
continue
# Decode and strip any html out of the field's help text
help_text = strip_tags(force_text(field.help_text))
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = force_text(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))
# Add the field's type to the docstring
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:
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)
# END Auto list fields from django models -
@ezeakeal-ps
Copy link

Thank you so much!

@cfingerh
Copy link

In Django 2.0.2 got an error in line 39
to = field.rel.to
and changed it to:
to = field.related_model

@mbambadev
Copy link

Thank so much all !

@ameamenoame
Copy link

This still works for 3.2.6, after chaing to = field.rel.to to to = field.related_model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment