coding-style.txt 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. ============
  2. Coding style
  3. ============
  4. Please follow these coding standards when writing code for inclusion in Django.
  5. Python style
  6. ------------
  7. * Please conform to the indentation style dictated in the ``.editorconfig``
  8. file. We recommend using a text editor with `EditorConfig`_ support to avoid
  9. indentation and whitespace issues. The Python files use 4 spaces for
  10. indentation and the HTML files use 2 spaces.
  11. * Unless otherwise specified, follow :pep:`8`.
  12. Use `flake8`_ to check for problems in this area. Note that our ``setup.cfg``
  13. file contains some excluded files (deprecated modules we don't care about
  14. cleaning up and some third-party code that Django vendors) as well as some
  15. excluded errors that we don't consider as gross violations. Remember that
  16. :pep:`8` is only a guide, so respect the style of the surrounding code as a
  17. primary goal.
  18. An exception to :pep:`8` is our rules on line lengths. Don't limit lines of
  19. code to 79 characters if it means the code looks significantly uglier or is
  20. harder to read. We allow up to 119 characters as this is the width of GitHub
  21. code review; anything longer requires horizontal scrolling which makes review
  22. more difficult. This check is included when you run ``flake8``. Documentation,
  23. comments, and docstrings should be wrapped at 79 characters, even though
  24. :pep:`8` suggests 72.
  25. * Use four spaces for indentation.
  26. * Use underscores, not camelCase, for variable, function and method names
  27. (i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters``).
  28. * Use ``InitialCaps`` for class names (or for factory functions that
  29. return classes).
  30. * In docstrings, follow :pep:`257`. For example::
  31. def foo():
  32. """
  33. Calculate something and return the result.
  34. """
  35. ...
  36. * In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` instead
  37. of :meth:`~unittest.TestCase.assertRaises` so you can check the exception
  38. message. Use :meth:`~unittest.TestCase.assertRaisesRegex`
  39. (``six.assertRaisesRegex()`` as long as we support Python 2) only if you need
  40. to use regular expression matching.
  41. Imports
  42. -------
  43. * Use `isort <https://github.com/timothycrosley/isort#readme>`_ to automate
  44. import sorting using the guidelines below.
  45. Quick start:
  46. .. code-block:: console
  47. $ pip install isort
  48. $ isort -rc .
  49. This runs ``isort`` recursively from your current directory, modifying any
  50. files that don't conform to the guidelines. If you need to have imports out
  51. of order (to avoid a circular import, for example) use a comment like this::
  52. import module # isort:skip
  53. * Put imports in these groups: future, standard library, third-party libraries,
  54. other Django components, local Django component, try/excepts. Sort lines in
  55. each group alphabetically by the full module name. Place all ``import module``
  56. statements before ``from module import objects`` in each section. Use absolute
  57. imports for other Django components and relative imports for local components.
  58. * On each line, alphabetize the items with the upper case items grouped before
  59. the lower case items.
  60. * Break long lines using parentheses and indent continuation lines by 4 spaces.
  61. Include a trailing comma after the last import and put the closing
  62. parenthesis on its own line.
  63. Use a single blank line between the last import and any module level code,
  64. and use two blank lines above the first function or class.
  65. For example (comments are for explanatory purposes only):
  66. .. snippet::
  67. :filename: django/contrib/admin/example.py
  68. # future
  69. from __future__ import unicode_literals
  70. # standard library
  71. import json
  72. from itertools import chain
  73. # third-party
  74. import bcrypt
  75. # Django
  76. from django.http import Http404
  77. from django.http.response import (
  78. Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse,
  79. cookie,
  80. )
  81. # local Django
  82. from .models import LogEntry
  83. # try/except
  84. try:
  85. import pytz
  86. except ImportError:
  87. pytz = None
  88. CONSTANT = 'foo'
  89. class Example(object):
  90. # ...
  91. * Use convenience imports whenever available. For example, do this::
  92. from django.views import View
  93. instead of::
  94. from django.views.generic.base import View
  95. Template style
  96. --------------
  97. * In Django template code, put one (and only one) space between the curly
  98. brackets and the tag contents.
  99. Do this:
  100. .. code-block:: html+django
  101. {{ foo }}
  102. Don't do this:
  103. .. code-block:: html+django
  104. {{foo}}
  105. View style
  106. ----------
  107. * In Django views, the first parameter in a view function should be called
  108. ``request``.
  109. Do this::
  110. def my_view(request, foo):
  111. # ...
  112. Don't do this::
  113. def my_view(req, foo):
  114. # ...
  115. Model style
  116. -----------
  117. * Field names should be all lowercase, using underscores instead of
  118. camelCase.
  119. Do this::
  120. class Person(models.Model):
  121. first_name = models.CharField(max_length=20)
  122. last_name = models.CharField(max_length=40)
  123. Don't do this::
  124. class Person(models.Model):
  125. FirstName = models.CharField(max_length=20)
  126. Last_Name = models.CharField(max_length=40)
  127. * The ``class Meta`` should appear *after* the fields are defined, with
  128. a single blank line separating the fields and the class definition.
  129. Do this::
  130. class Person(models.Model):
  131. first_name = models.CharField(max_length=20)
  132. last_name = models.CharField(max_length=40)
  133. class Meta:
  134. verbose_name_plural = 'people'
  135. Don't do this::
  136. class Person(models.Model):
  137. first_name = models.CharField(max_length=20)
  138. last_name = models.CharField(max_length=40)
  139. class Meta:
  140. verbose_name_plural = 'people'
  141. Don't do this, either::
  142. class Person(models.Model):
  143. class Meta:
  144. verbose_name_plural = 'people'
  145. first_name = models.CharField(max_length=20)
  146. last_name = models.CharField(max_length=40)
  147. * If you define a ``__str__`` method (previously ``__unicode__`` before Python 3
  148. was supported), decorate the model class with
  149. :func:`~django.utils.encoding.python_2_unicode_compatible`.
  150. * The order of model inner classes and standard methods should be as
  151. follows (noting that these are not all required):
  152. * All database fields
  153. * Custom manager attributes
  154. * ``class Meta``
  155. * ``def __str__()``
  156. * ``def save()``
  157. * ``def get_absolute_url()``
  158. * Any custom methods
  159. * If ``choices`` is defined for a given model field, define each choice as
  160. a tuple of tuples, with an all-uppercase name as a class attribute on the
  161. model. Example::
  162. class MyModel(models.Model):
  163. DIRECTION_UP = 'U'
  164. DIRECTION_DOWN = 'D'
  165. DIRECTION_CHOICES = (
  166. (DIRECTION_UP, 'Up'),
  167. (DIRECTION_DOWN, 'Down'),
  168. )
  169. Use of ``django.conf.settings``
  170. -------------------------------
  171. Modules should not in general use settings stored in ``django.conf.settings``
  172. at the top level (i.e. evaluated when the module is imported). The explanation
  173. for this is as follows:
  174. Manual configuration of settings (i.e. not relying on the
  175. ``DJANGO_SETTINGS_MODULE`` environment variable) is allowed and possible as
  176. follows::
  177. from django.conf import settings
  178. settings.configure({}, SOME_SETTING='foo')
  179. However, if any setting is accessed before the ``settings.configure`` line,
  180. this will not work. (Internally, ``settings`` is a ``LazyObject`` which
  181. configures itself automatically when the settings are accessed if it has not
  182. already been configured).
  183. So, if there is a module containing some code as follows::
  184. from django.conf import settings
  185. from django.urls import get_callable
  186. default_foo_view = get_callable(settings.FOO_VIEW)
  187. ...then importing this module will cause the settings object to be configured.
  188. That means that the ability for third parties to import the module at the top
  189. level is incompatible with the ability to configure the settings object
  190. manually, or makes it very difficult in some circumstances.
  191. Instead of the above code, a level of laziness or indirection must be used,
  192. such as ``django.utils.functional.LazyObject``,
  193. ``django.utils.functional.lazy()`` or ``lambda``.
  194. Miscellaneous
  195. -------------
  196. * Mark all strings for internationalization; see the :doc:`i18n
  197. documentation </topics/i18n/index>` for details.
  198. * Remove ``import`` statements that are no longer used when you change code.
  199. `flake8`_ will identify these imports for you. If an unused import needs to
  200. remain for backwards-compatibility, mark the end of with ``# NOQA`` to
  201. silence the flake8 warning.
  202. * Systematically remove all trailing whitespaces from your code as those
  203. add unnecessary bytes, add visual clutter to the patches and can also
  204. occasionally cause unnecessary merge conflicts. Some IDE's can be
  205. configured to automatically remove them and most VCS tools can be set to
  206. highlight them in diff outputs.
  207. * Please don't put your name in the code you contribute. Our policy is to
  208. keep contributors' names in the ``AUTHORS`` file distributed with Django
  209. -- not scattered throughout the codebase itself. Feel free to include a
  210. change to the ``AUTHORS`` file in your patch if you make more than a
  211. single trivial change.
  212. JavaScript style
  213. ----------------
  214. For details about the JavaScript code style used by Django, see
  215. :doc:`javascript`.
  216. .. _editorconfig: http://editorconfig.org/
  217. .. _flake8: https://pypi.python.org/pypi/flake8