2
0

coding-style.txt 9.5 KB

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