coding-style.txt 14 KB

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