Escrevendo a documentação¶
We place high importance on the consistency and readability of documentation. After all, Django was created in a journalism environment! So we treat our documentation like we treat our code: we aim to improve it as often as possible.
Mudanças na documentação geralmente aparecem de duas formas:
- Melhorias gerais: correção de ortografia, correções de erros e melhores explicações através de escrita clara e mais exemplos.
- Novas funcionalidades: documentação de funcionalidades que foram adicionadas ao framework desde a última release.
Esta seção explica como os escritores podem construir suas mudanças na documentação de forma mais eficiente e menos suscetível a erros.
The Django documentation process¶
Though Django’s documentation is intended to be read as HTML at https://docs.djangoproject.com/, we edit it as a collection of plain text files written in the reStructuredText markup language for maximum flexibility.
We work from the development version of the repository because it has the latest-and-greatest documentation, just as it has the latest-and-greatest code.
We also backport documentation fixes and improvements, at the discretion of the merger, to the last release branch. This is because it’s advantageous to have the docs for the last release be up-to-date and correct (see Diferenças entre versões).
A documentação do Django usa o sistema de documentação Sphinx, que por sua vez é baseado no docutils. A ideia básica é que uma documentação em texto plano com formatação simples é transformada em HTML, PDF, e muitos outros formatos.
Sphinx includes a sphinx-build
command for turning reStructuredText into
other formats, e.g., HTML and PDF. This command is configurable, but the Django
documentation includes a Makefile
that provides a shorter make html
command.
Como a documentação é organizada¶
A documentação é organizada em vários categorias:
Tutorials pega o leitor pelas mãos e o leva através de uma série de passos para criar algo.
O importante em um tutorial é ajudar o leitor a fazer algo útil, preferencialmente o mais rápido possível, para que ele passe a ganhar confiança.
Explain the nature of the problem we’re solving, so that the reader understands what we’re trying to achieve. Don’t feel that you need to begin with 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 and explain afterward.
Topic guides buscam explicar um conceito ou um assunto de modo bem abrangente.
Faça links para referências ao invés de repeti-las. Utilize exemplos e não seja relutante em explicar coisas que pareçam muito básicas para você - essa pode ser a explicação que outra pessoa precisa.
Contextualizar ajuda os novatos a ligar o assunto a coisas que eles já sabem.
Reference guides contain technical references for APIs. They describe the functioning of Django’s internal machinery and instruct in its use.
Mantenha o material de referência focado estritamente no assunto. Assuma que o leitor já entende os conceitos básicos envolvidos mas precisa saber ou ser lembrado de como o Django faz isso.
Guias de referência não são o local para explicações genéricas. Se você se encontrar explicando conceitos básicos, você deve querer mover o material para um guia em um assunto em específico.
How-to guides são receitas que levam o leitor através de uma série de passos em assuntos chave.
O que importa mais em um guia how-to é o que um usuário deseja alcançar. Um how-to deve sempre estar orientado a resultados ao invés de focado em detalhes internos de como o Django implementa o que quer que esteja sendo discutido.
Esses guias são mais avançados que tutoriais e assumem algum conhecimento sobre como o Django trabalha. Assuma que o leitor seguiu os tutoriais e não hesite em enviar o leitor de volta para o tutorial apropriado ao invés de repetir o mesmo material.
How to start contributing documentation¶
Clone the Django repository to your local machine¶
If you’d like to start contributing to our docs, get the development version of Django from the source code repository (see Instalando a versão de desenvolvimento.):
$ git clone https://github.com/django/django.git
...\> git clone https://github.com/django/django.git
If you’re planning to submit these changes, you might find it useful to make a fork of the Django repository and clone this fork instead.
Set up a virtual environment and install dependencies¶
Create and activate a virtual environment, then install the dependencies:
$ python -m venv .venv
$ source .venv/bin/activate
$ python -m pip install -r docs/requirements.txt
Build the documentation locally¶
We can build HTML output from the docs
directory:
$ cd docs
$ make html
...\> cd docs
...\> make.bat html
Your locally-built documentation will be accessible at
_build/html/index.html
and it can be viewed in any web browser, though it
will be themed differently than the documentation at
docs.djangoproject.com. This is OK! If
your changes look good on your local machine, they’ll look good on the website.
Making edits to the documentation¶
The source files are .txt
files located in the docs/
directory.
These files are written in the reStructuredText markup language. To learn the markup, see the reStructuredText reference.
To edit this page, for example, we would edit the file
docs/internals/contributing/writing-documentation.txt and rebuild the
HTML with make html
.
Verificação ortográfica¶
Before you commit your docs, it’s a good idea to run the spelling checker.
You’ll need to install sphinxcontrib-spelling first. Then 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
.
Se você encontrar falso-positivos (erros que na verdade estão corretos), faça uma das coisas a seguir:
- Surround inline code or brand/technology names with double grave accents (``).
- Encontre um sinônimo que o verificador ortográfico reconheça.
- Se, e somente se, você tiver certeza que a palavra que você está usando está correta - adicione ela em
docs/spelling_wordlist
(por favor mantenha a lista em ordem alfabética).
Link check¶
Links in documentation can become broken or changed such that they are no
longer the canonical link. Sphinx provides a builder that can check whether the
links in the documentation are working. From the docs
directory, run make
linkcheck
. Output is printed to the terminal, but can also be found in
_build/linkcheck/output.txt
and _build/linkcheck/output.json
.
Entries that have a status of “working” are fine, those that are “unchecked” or “ignored” have been skipped because they either cannot be checked or have matched ignore rules in the configuration.
Entries that have a status of “broken” need to be fixed. Those that have a
status of “redirected” may need to be updated to point to the canonical
location, e.g. the scheme has changed http://
→ https://
. In certain
cases, we do not want to update a “redirected” link, e.g. a rewrite to always
point to the latest or stable version of the documentation, e.g. /en/stable/
→
/en/3.2/
.
Estilo de escrita¶
When using pronouns in reference to a hypothetical person, such as “a user with a session cookie”, gender-neutral pronouns (they/their/them) should be used. Instead of:
- ele ou ela… utilize eles.
- Dele ou dela… utilize deles.
- Dele ou dela… utilize deles.
- dele ou dela… use deles.
- ele mesmo ou ela mesma… use eles mesmos.
Try to avoid using words that minimize the difficulty involved in a task or operation, such as “easily”, “simply”, “just”, “merely”, “straightforward”, and so on. People’s experience may not match your expectations, and they may become frustrated when they do not find a step as “straightforward” or “simple” as it is implied to be.
Termos usados com frequência¶
Aqui vão algumas orientações de estilo para termos usados comumente por toda a documentação:
- Django – quando estiver se referindo ao framework, deve começar com letra maiúscula. Ele só deve ser escrito em letras minúsculas no código Python e no logo de djangoproject.com.
- email – sem hífen.
- HTTP – the expected pronunciation is “Aitch Tee Tee Pee” and therefore should be preceded by “an” and not “a”.
- MySQL, PostgreSQL, SQLite
- SQL – quando estiver se referindo ao SQL, a pronunciação esperada deve ser “Ess Queue Ell” e não “sequel”. Portanto, em uma frase como “Retorna uma expressão SQL”, “SQL” deve ser precedido por “um” e não por “a”.
- Python – quando estiver se referindo a linguagem, use letra maiúscula.
- realize, customize, initialize, etc. – use o padrão Americano “ize” suffix, não “ise”
- subclass – É uma única palavra sem o hífen, tanto para o verbo (“subclassear o modelo”) quanto para o substântivo (“criar uma subclasse”).
- the web, web framework – it’s not capitalized.
- website – utilize uma palavra, tudo em minúsculas.
Terminologia específica do Django¶
- model – não tem maiúsculas.
- template – não tem maiúsculas.
- URLconf – utilize três as letras primeiras letras maiúsculas, sem espaço antes de “conf.”
- view – não tem maiúsculas.
Orientações gerais para arquivos reStructuredText¶
Estas regras regulam o formato de nossa documentação em reST (reStructuredText):
Na seção de títulos, só deixe em maiúsculas palavras iniciais e pronomes próprios.
Restrinja a documentação em até 80 caracteres de comprimento, a não ser que o código de exemplo seja significativamente mais difícil de ler quando quebrado em duas linhas, ou por outra boa razão.
The main thing to keep in mind as you write and edit docs is that the more semantic markup you can add the better. So:
Add ``django.contrib.auth`` to your ``INSTALLED_APPS``...
Isn’t nearly as helpful as:
Add :mod:`django.contrib.auth` to your :setting:`INSTALLED_APPS`...
Isso porque o Sphinx irá gerar links apropriados para o mais recente, o que ajuda muito os leitores.
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`
will display a link with the title “auth”.All Python code blocks should be formatted using the blacken-docs auto-formatter. This will be run by
pre-commit
if that is configured.Utilize
intersphinx
para referenciar a documentação do Python e do Sphinx.Add
.. code-block:: <lang>
to literal blocks so that they get highlighted. Prefer relying on automatic highlighting using::
(two colons). This has the benefit that if the code contains some invalid syntax, it won’t be highlighted. Adding.. code-block:: python
, for example, will force highlighting despite invalid syntax.To improve readability, use
.. admonition:: Descriptive title
rather than.. note::
. Use these boxes sparingly.Use these heading styles:
=== One === Two === Three ----- Four ~~~~ Five ^^^^
Use
:rfc:
to reference RFC and try to link to the relevant section if possible. For example, use:rfc:`2324#section-2.3.2`
or:rfc:`Custom link text <2324#section-2.3.2>`
.Use
:pep:
to reference a Python Enhancement Proposal (PEP) and try to link to the relevant section if possible. For example, use:pep:`20#easter-egg`
or:pep:`Easter Egg <20#easter-egg>`
.Use
:mimetype:
to refer to a MIME Type unless the value is quoted for a code example.Use
:envvar:
to refer to an environment variable. You may also need to define a reference to the documentation for that environment variable using.. envvar::
.
All Python code blocks in the Django documentation were reformatted with blacken-docs.
Marcação específica do Django¶
Besides Sphinx’s built-in markup, Django’s docs define some extra description units:
Settings:
.. setting:: INSTALLED_APPS
Para redirecionar para uma configuração, utilize
:setting:`INSTALLED_APPS`
.Template tags:
.. templatetag:: regroup
Para redirecionar, utilize
:ttag:`regroup`
.Template filters:
.. templatefilter:: linebreaksbr
Para redirecionar, utilize
:tfilter:`linebreaksbr`
.Field lookups (i.e.
Foo.objects.filter(bar__exact=whatever)
):.. fieldlookup:: exact
Para link, utilize
:lookup:`exact`
.django-admin
commands:.. django-admin:: migrate
Para linkar, utilize
:djadmin:`migrate`
.django-admin
command-line options:.. django-admin-option:: --traceback
Para redirecionar, utilize
:option:`command_name --traceback`
(ou omitacommand_name
para as opções compartilhadas por todos os comandos como--verbosity
).Links to Trac tickets (typically reserved for patch release notes):
:ticket:`12345`
Django’s documentation uses a custom console
directive for documenting
command-line examples involving django-admin
, manage.py
, python
,
etc.). In the HTML documentation, it renders a two-tab UI, with one tab showing
a Unix-style command prompt and a second tab showing a Windows prompt.
For example, you can replace this fragment:
use this command:
.. code-block:: console
$ python manage.py shell
with this one:
use this command:
.. console::
$ python manage.py shell
Note duas coisas:
- You usually will replace occurrences of the
.. code-block:: console
directive. - You don’t need to change the actual content of the code example. You still
write 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 first one will show:
$ python manage.py shell
(No changes from what .. code-block:: console
would have rendered).
O segundo irá mostrar:
...\> py manage.py shell
Documentando novas funcionalidades¶
Nossa política para novas funcionalidades é:
All documentation of new features should be written in a way that clearly designates the features that are only available in the Django development version. Assume documentation readers are using the latest release, not the development version.
Nossa forma preferida de marcar novas funcionalidades é adicionando um prefixo na documentação de novas funcionalidades com “.. versionadded:: X.Y
”, seguidas de uma linha em branco mandatória e uma descrição opcional (identada).
General improvements or other changes to the APIs that should be emphasized
should use the “.. versionchanged:: X.Y
” directive (with the same format
as 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 having
to reflow, reindent, or edit the surrounding text. For example, instead of
putting the entire description of a new or changed feature in a block, do
something like this:
.. class:: Author(first_name, last_name, middle_name=None)
A person who writes books.
``first_name`` is ...
...
``middle_name`` is ...
.. versionchanged:: A.B
The ``middle_name`` argument was added.
Coloque as considerações referentes as mudanças anotadas no final das seções, não no topo.
Além disso, evite mencionar uma versão específica do Django fora dos blocos versionadded
ou versionchanged
. Mesmo dentro de um bloco, Ainda costuma ser redundantes fazer isso já que essas anotações irão renderizar como “Novo no Django A.B” e “Alterado no Django A.B”, respectivamente.
If a function, attribute, etc. is added, it’s also okay to use a
versionadded
annotation like this:
.. attribute:: Author.middle_name
.. versionadded:: A.B
An author's middle name.
We can remove the .. versionadded:: A.B
annotation without any indentation
changes when the time comes.
Minimizando imagens¶
Otimize a compressão das imagens quando possível. Para arquivos PNG, utilize OptiPNG e o “advpng” da AdvanceCOMP:
$ cd docs
$ optipng -o7 -zm1-9 -i0 -strip all `find . -type f -not -path "./_build/*" -name "*.png"`
$ 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.
Um exemplo¶
Para um rápido exemplo de como tudo se encaixa, considere este exemplo hipotético:
Primeiro, o documento
ref/settings.txt
pode ter um leiaute geral como esse:======== Settings ======== ... .. _available-settings: Available settings ================== ... .. _deprecated-settings: Deprecated settings =================== ...
Depois, o documento
topics/settings.txt
pode ser algo assim:You can access a :ref:`listing of all available settings <available-settings>`. For a list of deprecated settings see :ref:`deprecated-settings`. You can find both in the :doc:`settings reference document </ref/settings>`.
We use the Sphinx
doc
cross-reference element when we want to link to another document as a whole and theref
element when we want to link to an arbitrary location in a document.Depois, repare em como os settings são anotados:
.. setting:: ADMINS ADMINS ====== Default: ``[]`` (Empty list) A list of all the people who get code error notifications. When ``DEBUG=False`` and a view raises an exception, Django will email these people with the full exception information. Each member of the list should be a tuple of (Full name, email address). Example:: [("John", "john@example.com"), ("Mary", "mary@example.com")] Note that Django will email *all* of these people whenever an error happens. See :doc:`/howto/error-reporting` for more information.
Isso marca o próximo cabeçalho como o alvo “canônico” para o setting
ADMINS
. Isto significa que sempre que eu falar sobreADMINS
, eu posso redirecionar para ele usando:setting:`ADMINS`
.
Isso é basicamente como tudo se encaixa.
Traduzindo a documentação¶
Veja Localizing the Django documentation Se você quer ajudar a traduzir a documentação para outras linguagens.
Página man do django-admin
¶
O Sphinx pode gerar uma página de manual para o comando django-admin. Isso é configurado em docs/conf.py
. Diferentemente de outras documentações geradas, essa página man deve ser incluída no repositório do Django e de suas releases em docs/man/django-admin.1
. Não existe a necessidade de atualizar esse arquivo quando estiver atualizando a documentação, já que ele é atualizado durante o processo de release.
Para gerar uma versão atualizada da página man, roda o comando make man
dentro do diretório docs
. A nova página man será escrita em docs/_build/man/django-admin.1
.