coding-style.txt 12 KB

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