coding-style.txt 9.0 KB

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