coding-style.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. ============
  2. Coding style
  3. ============
  4. Please follow these coding standards when writing code for inclusion in Django.
  5. .. _coding-style-pre-commit:
  6. Pre-commit checks
  7. =================
  8. `pre-commit <https://pre-commit.com>`_ is a framework for managing pre-commit
  9. hooks. These hooks help to identify simple issues before committing code for
  10. review. By checking for these issues before code review it allows the reviewer
  11. to focus on the change itself, and it can also help to reduce the number CI
  12. runs.
  13. To use the tool, first install ``pre-commit`` and then the git hooks:
  14. .. console::
  15. $ python -m pip install pre-commit
  16. $ pre-commit install
  17. On the first commit ``pre-commit`` will install the hooks, these are
  18. installed in their own environments and will take a short while to
  19. install on the first run. Subsequent checks will be significantly faster.
  20. If an error is found an appropriate error message will be displayed.
  21. If the error was with ``isort`` then the tool will go ahead and fix them for
  22. you. Review the changes and re-stage for commit if you are happy with
  23. them.
  24. .. _coding-style-python:
  25. Python style
  26. ============
  27. * Please conform to the indentation style dictated in the ``.editorconfig``
  28. file. We recommend using a text editor with `EditorConfig`_ support to avoid
  29. indentation and whitespace issues. The Python files use 4 spaces for
  30. indentation and the HTML files use 2 spaces.
  31. * Unless otherwise specified, follow :pep:`8`.
  32. Use `flake8`_ to check for problems in this area. Note that our ``setup.cfg``
  33. file contains some excluded files (deprecated modules we don't care about
  34. cleaning up and some third-party code that Django vendors) as well as some
  35. excluded errors that we don't consider as gross violations. Remember that
  36. :pep:`8` is only a guide, so respect the style of the surrounding code as a
  37. primary goal.
  38. An exception to :pep:`8` is our rules on line lengths. Don't limit lines of
  39. code to 79 characters if it means the code looks significantly uglier or is
  40. harder to read. We allow up to 119 characters as this is the width of GitHub
  41. code review; anything longer requires horizontal scrolling which makes review
  42. more difficult. This check is included when you run ``flake8``. Documentation,
  43. comments, and docstrings should be wrapped at 79 characters, even though
  44. :pep:`8` suggests 72.
  45. * Use four spaces for indentation.
  46. * Use four space hanging indentation rather than vertical alignment::
  47. raise AttributeError(
  48. 'Here is a multiline error message '
  49. 'shortened for clarity.'
  50. )
  51. Instead of::
  52. raise AttributeError('Here is a multiline error message '
  53. 'shortened for clarity.')
  54. This makes better use of space and avoids having to realign strings if the
  55. length of the first line changes.
  56. * Use single quotes for strings, or a double quote if the string contains a
  57. single quote. Don't waste time doing unrelated refactoring of existing code
  58. to conform to this style.
  59. * String variable interpolation may use
  60. :py:ref:`%-formatting <old-string-formatting>`, :py:ref:`f-strings
  61. <f-strings>`, or :py:meth:`str.format` as appropriate, with the goal of
  62. maximizing code readability.
  63. Final judgments of readability are left to the Merger's discretion. As a
  64. guide, f-strings should use only plain variable and property access, with
  65. prior local variable assignment for more complex cases::
  66. # Allowed
  67. f'hello {user}'
  68. f'hello {user.name}'
  69. f'hello {self.user.name}'
  70. # Disallowed
  71. f'hello {get_user()}'
  72. f'you are {user.age * 365.25} days old'
  73. # Allowed with local variable assignment
  74. user = get_user()
  75. f'hello {user}'
  76. user_days_old = user.age * 365.25
  77. f'you are {user_days_old} days old'
  78. f-strings should not be used for any string that may require translation,
  79. including error and logging messages. In general ``format()`` is more
  80. verbose, so the other formatting methods are preferred.
  81. Don't waste time doing unrelated refactoring of existing code to adjust the
  82. formatting method.
  83. * Avoid use of "we" in comments, e.g. "Loop over" rather than "We loop over".
  84. * Use underscores, not camelCase, for variable, function and method names
  85. (i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters()``).
  86. * Use ``InitialCaps`` for class names (or for factory functions that
  87. return classes).
  88. * In docstrings, follow the style of existing docstrings and :pep:`257`.
  89. * In tests, use
  90. :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and
  91. :meth:`~django.test.SimpleTestCase.assertWarnsMessage`
  92. instead of :meth:`~unittest.TestCase.assertRaises` and
  93. :meth:`~unittest.TestCase.assertWarns` so you can check the
  94. exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex`
  95. and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular
  96. expression matching.
  97. Use :meth:`assertIs(…, True/False)<unittest.TestCase.assertIs>` for testing
  98. boolean values, rather than :meth:`~unittest.TestCase.assertTrue` and
  99. :meth:`~unittest.TestCase.assertFalse`, so you can check the actual boolean
  100. value, not the truthiness of the expression.
  101. * In test docstrings, state the expected behavior that each test demonstrates.
  102. Don't include preambles such as "Tests that" or "Ensures that".
  103. Reserve ticket references for obscure issues where the ticket has additional
  104. details that can't be easily described in docstrings or comments. Include the
  105. ticket number at the end of a sentence like this::
  106. def test_foo():
  107. """
  108. A test docstring looks like this (#123456).
  109. """
  110. ...
  111. .. _coding-style-imports:
  112. Imports
  113. =======
  114. * Use `isort <https://github.com/PyCQA/isort#readme>`_ to automate import
  115. sorting using the guidelines below.
  116. Quick start:
  117. .. console::
  118. $ python -m pip install isort >= 5.1.0
  119. $ isort -rc .
  120. This runs ``isort`` recursively from your current directory, modifying any
  121. files that don't conform to the guidelines. If you need to have imports out
  122. of order (to avoid a circular import, for example) use a comment like this::
  123. import module # isort:skip
  124. * Put imports in these groups: future, standard library, third-party libraries,
  125. other Django components, local Django component, try/excepts. Sort lines in
  126. each group alphabetically by the full module name. Place all ``import module``
  127. statements before ``from module import objects`` in each section. Use absolute
  128. imports for other Django components and relative imports for local components.
  129. * On each line, alphabetize the items with the upper case items grouped before
  130. the lowercase items.
  131. * Break long lines using parentheses and indent continuation lines by 4 spaces.
  132. Include a trailing comma after the last import and put the closing
  133. parenthesis on its own line.
  134. Use a single blank line between the last import and any module level code,
  135. and use two blank lines above the first function or class.
  136. For example (comments are for explanatory purposes only):
  137. .. code-block:: python
  138. :caption: django/contrib/admin/example.py
  139. # future
  140. from __future__ import unicode_literals
  141. # standard library
  142. import json
  143. from itertools import chain
  144. # third-party
  145. import bcrypt
  146. # Django
  147. from django.http import Http404
  148. from django.http.response import (
  149. Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse,
  150. cookie,
  151. )
  152. # local Django
  153. from .models import LogEntry
  154. # try/except
  155. try:
  156. import yaml
  157. except ImportError:
  158. yaml = None
  159. CONSTANT = 'foo'
  160. class Example:
  161. # ...
  162. * Use convenience imports whenever available. For example, do this::
  163. from django.views import View
  164. instead of::
  165. from django.views.generic.base import View
  166. Template style
  167. ==============
  168. * In Django template code, put one (and only one) space between the curly
  169. brackets and the tag contents.
  170. Do this:
  171. .. code-block:: html+django
  172. {{ foo }}
  173. Don't do this:
  174. .. code-block:: html+django
  175. {{foo}}
  176. View style
  177. ==========
  178. * In Django views, the first parameter in a view function should be called
  179. ``request``.
  180. Do this::
  181. def my_view(request, foo):
  182. # ...
  183. Don't do this::
  184. def my_view(req, foo):
  185. # ...
  186. Model style
  187. ===========
  188. * Field names should be all lowercase, using underscores instead of
  189. camelCase.
  190. Do this::
  191. class Person(models.Model):
  192. first_name = models.CharField(max_length=20)
  193. last_name = models.CharField(max_length=40)
  194. Don't do this::
  195. class Person(models.Model):
  196. FirstName = models.CharField(max_length=20)
  197. Last_Name = models.CharField(max_length=40)
  198. * The ``class Meta`` should appear *after* the fields are defined, with
  199. a single blank line separating the fields and the class definition.
  200. Do this::
  201. class Person(models.Model):
  202. first_name = models.CharField(max_length=20)
  203. last_name = models.CharField(max_length=40)
  204. class Meta:
  205. verbose_name_plural = 'people'
  206. Don't do this::
  207. class Person(models.Model):
  208. first_name = models.CharField(max_length=20)
  209. last_name = models.CharField(max_length=40)
  210. class Meta:
  211. verbose_name_plural = 'people'
  212. Don't do this, either::
  213. class Person(models.Model):
  214. class Meta:
  215. verbose_name_plural = 'people'
  216. first_name = models.CharField(max_length=20)
  217. last_name = models.CharField(max_length=40)
  218. * The order of model inner classes and standard methods should be as
  219. follows (noting that these are not all required):
  220. * All database fields
  221. * Custom manager attributes
  222. * ``class Meta``
  223. * ``def __str__()``
  224. * ``def save()``
  225. * ``def get_absolute_url()``
  226. * Any custom methods
  227. * If ``choices`` is defined for a given model field, define each choice as a
  228. list of tuples, with an all-uppercase name as a class attribute on the model.
  229. Example::
  230. class MyModel(models.Model):
  231. DIRECTION_UP = 'U'
  232. DIRECTION_DOWN = 'D'
  233. DIRECTION_CHOICES = [
  234. (DIRECTION_UP, 'Up'),
  235. (DIRECTION_DOWN, 'Down'),
  236. ]
  237. Use of ``django.conf.settings``
  238. ===============================
  239. Modules should not in general use settings stored in ``django.conf.settings``
  240. at the top level (i.e. evaluated when the module is imported). The explanation
  241. for this is as follows:
  242. Manual configuration of settings (i.e. not relying on the
  243. :envvar:`DJANGO_SETTINGS_MODULE` environment variable) is allowed and possible
  244. as follows::
  245. from django.conf import settings
  246. settings.configure({}, SOME_SETTING='foo')
  247. However, if any setting is accessed before the ``settings.configure`` line,
  248. this will not work. (Internally, ``settings`` is a ``LazyObject`` which
  249. configures itself automatically when the settings are accessed if it has not
  250. already been configured).
  251. So, if there is a module containing some code as follows::
  252. from django.conf import settings
  253. from django.urls import get_callable
  254. default_foo_view = get_callable(settings.FOO_VIEW)
  255. ...then importing this module will cause the settings object to be configured.
  256. That means that the ability for third parties to import the module at the top
  257. level is incompatible with the ability to configure the settings object
  258. manually, or makes it very difficult in some circumstances.
  259. Instead of the above code, a level of laziness or indirection must be used,
  260. such as ``django.utils.functional.LazyObject``,
  261. ``django.utils.functional.lazy()`` or ``lambda``.
  262. Miscellaneous
  263. =============
  264. * Mark all strings for internationalization; see the :doc:`i18n
  265. documentation </topics/i18n/index>` for details.
  266. * Remove ``import`` statements that are no longer used when you change code.
  267. `flake8`_ will identify these imports for you. If an unused import needs to
  268. remain for backwards-compatibility, mark the end of with ``# NOQA`` to
  269. silence the flake8 warning.
  270. * Systematically remove all trailing whitespaces from your code as those
  271. add unnecessary bytes, add visual clutter to the patches and can also
  272. occasionally cause unnecessary merge conflicts. Some IDE's can be
  273. configured to automatically remove them and most VCS tools can be set to
  274. highlight them in diff outputs.
  275. * Please don't put your name in the code you contribute. Our policy is to
  276. keep contributors' names in the ``AUTHORS`` file distributed with Django
  277. -- not scattered throughout the codebase itself. Feel free to include a
  278. change to the ``AUTHORS`` file in your patch if you make more than a
  279. single trivial change.
  280. JavaScript style
  281. ================
  282. For details about the JavaScript code style used by Django, see
  283. :doc:`javascript`.
  284. .. _editorconfig: https://editorconfig.org/
  285. .. _flake8: https://pypi.org/project/flake8/