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