Writing documentation

We place a high importance on consistency and readability of documentation.After all, Django was created in a journalism environment! So we treat ourdocumentation like we treat our code: we aim to improve it as often aspossible.

Documentation changes generally come in two forms:

  • General improvements: typo corrections, error fixes and betterexplanations through clearer writing and more examples.
  • New features: documentation of features that have been added to theframework since the last release.This section explains how writers can craft their documentation changesin the most useful and least error-prone ways.

Getting the raw documentation

Though Django’s documentation is intended to be read as HTML athttps://docs.djangoproject.com/, we edit it as a collection of text files formaximum flexibility. These files live in the top-level docs/ directory of aDjango release.

If you’d like to start contributing to our docs, get the development version ofDjango from the source code repository(see Installing the development version). The development version has thelatest-and-greatest documentation, just as it has latest-and-greatest code.We also backport documentation fixes and improvements, at the discretion of thecommitter, to the last release branch. That’s because it’s highly advantageousto have the docs for the last release be up-to-date and correct (seeDifferences between versions).

Getting started with Sphinx

Django’s documentation uses the Sphinx documentation system, which in turnis based on docutils. The basic idea is that lightly-formatted plain-textdocumentation is transformed into HTML, PDF, and any other output format.

To build the documentation locally, install Sphinx:

  1. $ python -m pip install Sphinx
  1. ...\> py -m pip install Sphinx

Then from the docs directory, build the HTML:

  1. $ make html
  1. ...\> make.bat html

To get started contributing, you’ll want to read the reStructuredTextreference.

Your locally-built documentation will be themed differently than thedocumentation at docs.djangoproject.com.This is OK! If your changes look good on your local machine, they’ll look goodon the website.

How the documentation is organized

The documentation is organized into several categories:

  • Tutorials take the reader by the hand through a seriesof steps to create something.

The important thing in a tutorial is to help the reader achieve somethinguseful, preferably as early as possible, in order to give them confidence.

Explain the nature of the problem we’re solving, so that the readerunderstands what we’re trying to achieve. Don’t feel that you need to beginwith explanations of how things work - what matters is what the reader does,not what you explain. It can be helpful to refer back to what you’ve done andexplain afterwards.

  • Topic guides aim to explain a concept or subject at afairly high level.

Link to reference material rather than repeat it. Use examples and don’t bereluctant to explain things that seem very basic to you - it might be theexplanation someone else needs.

Providing background context helps a newcomer connect the topic to thingsthat they already know.

  • Reference guides contain technical reference for APIs.They describe the functioning of Django’s internal machinery and instruct inits use.

Keep reference material tightly focused on the subject. Assume that thereader already understands the basic concepts involved but needs to know orbe reminded of how Django does it.

Reference guides aren’t the place for general explanation. If you findyourself explaining basic concepts, you may want to move that material to atopic guide.

  • How-to guides are recipes that take the reader throughsteps in key subjects.

What matters most in a how-to guide is what a user wants to achieve.A how-to should always be result-oriented rather than focused on internaldetails of how Django implements whatever is being discussed.

These guides are more advanced than tutorials and assume some knowledge abouthow Django works. Assume that the reader has followed the tutorials and don’thesitate to refer the reader back to the appropriate tutorial rather thanrepeat the same material.

Writing style

When using pronouns in reference to a hypothetical person, such as “a user witha session cookie”, gender neutral pronouns (they/their/them) should be used.Instead of:

  • he or she… use they.
  • him or her… use them.
  • his or her… use their.
  • his or hers… use theirs.
  • himself or herself… use themselves.Try to avoid using words that minimize the difficulty involved in a task oroperation, such as “easily”, “simply”, “just”, “merely”, “straightforward”, andso on. People’s experience may not match your expectations, and they may becomefrustrated when they do not find a step as “straightforward” or “simple” as itis implied to be.

Commonly used terms

Here are some style guidelines on commonly used terms throughout thedocumentation:

  • Django – when referring to the framework, capitalize Django. It islowercase only in Python code and in the djangoproject.com logo.
  • email – no hyphen.
  • MySQL, PostgreSQL, SQLite
  • SQL – when referring to SQL, the expected pronunciation should be“Ess Queue Ell” and not “sequel”. Thus in a phrase like “Returns anSQL expression”, “SQL” should be preceded by “an” and not “a”.
  • Python – when referring to the language, capitalize Python.
  • realize, customize, initialize, etc. – use the American“ize” suffix, not “ise.”
  • subclass – it’s a single word without a hyphen, both as a verb(“subclass that model”) and as a noun (“create a subclass”).
  • Web, World Wide Web, the Web – note Web is alwayscapitalized when referring to the World Wide Web.
  • website – use one word, without capitalization.

Django-specific terminology

  • model – it’s not capitalized.
  • template – it’s not capitalized.
  • URLconf – use three capitalized letters, with no space before“conf.”
  • view – it’s not capitalized.

Guidelines for reStructuredText files

These guidelines regulate the format of our reST (reStructuredText)documentation:

  • In section titles, capitalize only initial words and proper nouns.

  • Wrap the documentation at 80 characters wide, unless a code exampleis significantly less readable when split over two lines, or for anothergood reason.

  • The main thing to keep in mind as you write and edit docs is that themore semantic markup you can add the better. So:

  1. Add ``django.contrib.auth`` to your ``INSTALLED_APPS``...

Isn’t nearly as helpful as:

  1. Add :mod:`django.contrib.auth` to your :setting:`INSTALLED_APPS`...

This is because Sphinx will generate proper links for the latter, whichgreatly helps readers.

You can prefix the target with a ~ (that’s a tilde) to get only the“last bit” of that path. So :mod:~django.contrib.auth willdisplay a link with the title “auth”.

  • Use intersphinx to reference Python’s and Sphinx’documentation.

  • Add .. code-block:: <lang> to literal blocks so that they gethighlighted. Prefer relying on automatic highlighting using ::(two colons). This has the benefit that if the code contains some invalidsyntax, it won’t be highlighted. Adding .. code-block:: python, forexample, will force highlighting despite invalid syntax.

  • To improve readability, use .. admonition:: Descriptive title rather than.. note::. Use these boxes sparingly.

  • Use these heading styles:

  1. ===
  2. One
  3. ===
  4.  
  5. Two
  6. ===
  7.  
  8. Three
  9. -----
  10.  
  11. Four
  12. ~~~~
  13.  
  14. Five
  15. ^^^^

Django-specific markup

Besides Sphinx’s built-in markup, Django’s docsdefine some extra description units:

  • Settings:
  1. .. setting:: INSTALLED_APPS

To link to a setting, use :setting:INSTALLED_APPS.

  • Template tags:
  1. .. templatetag:: regroup

To link, use :ttag:regroup.

  • Template filters:
  1. .. templatefilter:: linebreaksbr

To link, use :tfilter:linebreaksbr.

  • Field lookups (i.e. Foo.objects.filter(bar__exact=whatever)):
  1. .. fieldlookup:: exact

To link, use :lookup:exact.

  • django-admin commands:
  1. .. django-admin:: migrate

To link, use :djadmin:migrate.

  • django-admin command-line options:
  1. .. django-admin-option:: --traceback

To link, use :option:command_name --traceback (or omit command_namefor the options shared by all commands like —verbosity).

  • Links to Trac tickets (typically reserved for patch release notes):
  1. :ticket:`12345`

Django’s documentation uses a custom console directive for documentingcommand-line examples involving django-admin.py, manage.py, python,etc.). In the HTML documentation, it renders a two-tab UI, with one tab showinga Unix-style command prompt and a second tab showing a Windows prompt.

For example, you can replace this fragment:

  1. use this command:
  2.  
  3. .. code-block:: console
  4.  
  5. $ python manage.py shell

with this one:

  1. use this command:
  2.  
  3. .. console::
  4.  
  5. $ python manage.py shell

Notice two things:

  • You usually will replace occurrences of the .. code-block:: consoledirective.
  • You don’t need to change the actual content of the code example. You stillwrite it assuming a Unix-y environment (i.e. a '$' prompt symbol,'/' as filesystem path components separator, etc.)The example above will render a code example block with two tabs. The firstone will show:
  1. $ python manage.py shell

(No changes from what .. code-block:: console would have rendered).

The second one will show:

  1. ...\> py manage.py shell

Documenting new features

Our policy for new features is:

All documentation of new features should be written in a way thatclearly designates the features are only available in the Djangodevelopment version. Assume documentation readers are using the latestrelease, not the development version.

Our preferred way for marking new features is by prefacing the features’documentation with: “.. versionadded:: X.Y”, followed by a mandatoryblank line and an optional description (indented).

General improvements, or other changes to the APIs that should be emphasizedshould use the “.. versionchanged:: X.Y” directive (with the same formatas the versionadded mentioned above.

These versionadded and versionchanged blocks should be “self-contained.”In other words, since we only keep these annotations around for two releases,it’s nice to be able to remove the annotation and its contents without havingto reflow, reindent, or edit the surrounding text. For example, instead ofputting the entire description of a new or changed feature in a block, dosomething like this:

  1. .. class:: Author(first_name, last_name, middle_name=None)
  2.  
  3. A person who writes books.
  4.  
  5. ``first_name`` is ...
  6.  
  7. ...
  8.  
  9. ``middle_name`` is ...
  10.  
  11. .. versionchanged:: A.B
  12.  
  13. The ``middle_name`` argument was added.

Put the changed annotation notes at the bottom of a section, not the top.

Also, avoid referring to a specific version of Django outside aversionadded or versionchanged block. Even inside a block, it’s oftenredundant to do so as these annotations render as “New in Django A.B:” and“Changed in Django A.B”, respectively.

If a function, attribute, etc. is added, it’s also okay to use aversionadded annotation like this:

  1. .. attribute:: Author.middle_name
  2.  
  3. .. versionadded:: A.B
  4.  
  5. An author's middle name.

We can remove the .. versionadded:: A.B annotation without any indentationchanges when the time comes.

Minimizing images

Optimize image compression where possible. For PNG files, use OptiPNG andAdvanceCOMP’s advpng:

  1. $ cd docs
  2. $ optipng -o7 -zm1-9 -i0 -strip all `find . -type f -not -path "./_build/*" -name "*.png"`
  3. $ advpng -z4 `find . -type f -not -path "./_build/*" -name "*.png"`

This is based on OptiPNG version 0.7.5. Older versions may complain about the—strip all option being lossy.

An example

For a quick example of how it all fits together, consider this hypotheticalexample:

  • First, the ref/settings.txt document could have an overall layoutlike this:
  1. ========
  2. Settings
  3. ========
  4.  
  5. ...
  6.  
  7. .. _available-settings:
  8.  
  9. Available settings
  10. ==================
  11.  
  12. ...
  13.  
  14. .. _deprecated-settings:
  15.  
  16. Deprecated settings
  17. ===================
  18.  
  19. ...
  • Next, the topics/settings.txt document could contain something likethis:
  1. You can access a :ref:`listing of all available settings
  2. <available-settings>`. For a list of deprecated settings see
  3. :ref:`deprecated-settings`.
  4.  
  5. You can find both in the :doc:`settings reference document
  6. </ref/settings>`.

We use the Sphinx doc cross reference element when we want tolink to another document as a whole and the ref element whenwe want to link to an arbitrary location in a document.

  • Next, notice how the settings are annotated:
  1. .. setting:: ADMINS
  2.  
  3. ADMINS
  4. ======
  5.  
  6. Default: ``[]`` (Empty list)
  7.  
  8. A list of all the people who get code error notifications. When
  9. ``DEBUG=False`` and a view raises an exception, Django will email these people
  10. with the full exception information. Each member of the list should be a tuple
  11. of (Full name, email address). Example::
  12.  
  13. [('John', 'john@example.com'), ('Mary', 'mary@example.com')]
  14.  
  15. Note that Django will email *all* of these people whenever an error happens.
  16. See :doc:`/howto/error-reporting` for more information.

This marks up the following header as the “canonical” target for thesetting ADMINS. This means any time I talk about ADMINS,I can reference it using :setting:ADMINS.

That’s basically how everything fits together.

Spelling check

Before you commit your docs, it’s a good idea to run the spelling checker.You’ll need to install a couple packages first:

  • pyenchant (which requiresenchant)
  • sphinxcontrib-spellingThen from the docs directory, run make spelling. Wrong words (if any)along with the file and line number where they occur will be saved to_build/spelling/output.txt.

If you encounter false-positives (error output that actually is correct), doone of the following:

  • Surround inline code or brand/technology names with grave accents (`).
  • Find synonyms that the spell checker recognizes.
  • If, and only if, you are sure the word you are using is correct - add itto docs/spelling_wordlist (please keep the list in alphabetical order).

Translating documentation

See Localizing the Django documentation ifyou’d like to help translate the documentation into another language.

django-admin man page

Sphinx can generate a manual page for thedjango-admin command. This is configured indocs/conf.py. Unlike other documentation output, this man page should beincluded in the Django repository and the releases asdocs/man/django-admin.1. There isn’t a need to update this file whenupdating the documentation, as it’s updated once as part of the release process.

To generate an updated version of the man page, run make man in thedocs directory. The new man page will be written indocs/_build/man/django-admin.1.