coding-style.txt 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. ============
  2. Coding style
  3. ============
  4. Please follow these coding standards when writing code for inclusion in Django.
  5. Python style
  6. ------------
  7. * Unless otherwise specified, follow :pep:`8`.
  8. Use `flake8`_ to check for problems in this area. Note that our ``setup.cfg``
  9. file contains some excluded files (deprecated modules we don't care about
  10. cleaning up and some third-party code that Django vendors) as well as some
  11. excluded errors that we don't consider as gross violations. Remember that
  12. :pep:`8` is only a guide, so respect the style of the surrounding code as a
  13. primary goal.
  14. One big exception to :pep:`8` is our preference of longer line lengths.
  15. We're well into the 21st Century, and we have high-resolution computer
  16. screens that can fit way more than 79 characters on a screen. Don't limit
  17. lines of code to 79 characters if it means the code looks significantly
  18. uglier or is harder to read.
  19. * Use four spaces for indentation.
  20. * Use underscores, not camelCase, for variable, function and method names
  21. (i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters``).
  22. * Use ``InitialCaps`` for class names (or for factory functions that
  23. return classes).
  24. * Use convenience imports whenever available. For example, do this::
  25. from django.views.generic import View
  26. Don't do this::
  27. from django.views.generic.base import View
  28. * In docstrings, use "action words" such as::
  29. def foo():
  30. """
  31. Calculates something and returns the result.
  32. """
  33. pass
  34. Here's an example of what not to do::
  35. def foo():
  36. """
  37. Calculate something and return the result.
  38. """
  39. pass
  40. Template style
  41. --------------
  42. * In Django template code, put one (and only one) space between the curly
  43. brackets and the tag contents.
  44. Do this:
  45. .. code-block:: html+django
  46. {{ foo }}
  47. Don't do this:
  48. .. code-block:: html+django
  49. {{foo}}
  50. View style
  51. ----------
  52. * In Django views, the first parameter in a view function should be called
  53. ``request``.
  54. Do this::
  55. def my_view(request, foo):
  56. # ...
  57. Don't do this::
  58. def my_view(req, foo):
  59. # ...
  60. Model style
  61. -----------
  62. * Field names should be all lowercase, using underscores instead of
  63. camelCase.
  64. Do this::
  65. class Person(models.Model):
  66. first_name = models.CharField(max_length=20)
  67. last_name = models.CharField(max_length=40)
  68. Don't do this::
  69. class Person(models.Model):
  70. FirstName = models.CharField(max_length=20)
  71. Last_Name = models.CharField(max_length=40)
  72. * The ``class Meta`` should appear *after* the fields are defined, with
  73. a single blank line separating the fields and the class definition.
  74. Do this::
  75. class Person(models.Model):
  76. first_name = models.CharField(max_length=20)
  77. last_name = models.CharField(max_length=40)
  78. class Meta:
  79. verbose_name_plural = 'people'
  80. Don't do this::
  81. class Person(models.Model):
  82. first_name = models.CharField(max_length=20)
  83. last_name = models.CharField(max_length=40)
  84. class Meta:
  85. verbose_name_plural = 'people'
  86. Don't do this, either::
  87. class Person(models.Model):
  88. class Meta:
  89. verbose_name_plural = 'people'
  90. first_name = models.CharField(max_length=20)
  91. last_name = models.CharField(max_length=40)
  92. * If you define a ``__str__`` method (previously ``__unicode__`` before Python 3
  93. was supported), decorate the model class with
  94. :func:`~django.utils.encoding.python_2_unicode_compatible`.
  95. * The order of model inner classes and standard methods should be as
  96. follows (noting that these are not all required):
  97. * All database fields
  98. * Custom manager attributes
  99. * ``class Meta``
  100. * ``def __str__()``
  101. * ``def save()``
  102. * ``def get_absolute_url()``
  103. * Any custom methods
  104. * If ``choices`` is defined for a given model field, define each choice as
  105. a tuple of tuples, with an all-uppercase name as a class attribute on the
  106. model. Example::
  107. class MyModel(models.Model):
  108. DIRECTION_UP = 'U'
  109. DIRECTION_DOWN = 'D'
  110. DIRECTION_CHOICES = (
  111. (DIRECTION_UP, 'Up'),
  112. (DIRECTION_DOWN, 'Down'),
  113. )
  114. Use of ``django.conf.settings``
  115. -------------------------------
  116. Modules should not in general use settings stored in ``django.conf.settings``
  117. at the top level (i.e. evaluated when the module is imported). The explanation
  118. for this is as follows:
  119. Manual configuration of settings (i.e. not relying on the
  120. ``DJANGO_SETTINGS_MODULE`` environment variable) is allowed and possible as
  121. follows::
  122. from django.conf import settings
  123. settings.configure({}, SOME_SETTING='foo')
  124. However, if any setting is accessed before the ``settings.configure`` line,
  125. this will not work. (Internally, ``settings`` is a ``LazyObject`` which
  126. configures itself automatically when the settings are accessed if it has not
  127. already been configured).
  128. So, if there is a module containing some code as follows::
  129. from django.conf import settings
  130. from django.core.urlresolvers import get_callable
  131. default_foo_view = get_callable(settings.FOO_VIEW)
  132. ...then importing this module will cause the settings object to be configured.
  133. That means that the ability for third parties to import the module at the top
  134. level is incompatible with the ability to configure the settings object
  135. manually, or makes it very difficult in some circumstances.
  136. Instead of the above code, a level of laziness or indirection must be used,
  137. such as ``django.utils.functional.LazyObject``,
  138. ``django.utils.functional.lazy()`` or ``lambda``.
  139. Miscellaneous
  140. -------------
  141. * Mark all strings for internationalization; see the :doc:`i18n
  142. documentation </topics/i18n/index>` for details.
  143. * Remove ``import`` statements that are no longer used when you change code.
  144. `flake8`_ will identify these imports for you. If an unused import needs to
  145. remain for backwards-compatibility, mark the end of with ``# NOQA`` to
  146. silence the flake8 warning.
  147. * Systematically remove all trailing whitespaces from your code as those
  148. add unnecessary bytes, add visual clutter to the patches and can also
  149. occasionally cause unnecessary merge conflicts. Some IDE's can be
  150. configured to automatically remove them and most VCS tools can be set to
  151. highlight them in diff outputs.
  152. * Please don't put your name in the code you contribute. Our policy is to
  153. keep contributors' names in the ``AUTHORS`` file distributed with Django
  154. -- not scattered throughout the codebase itself. Feel free to include a
  155. change to the ``AUTHORS`` file in your patch if you make more than a
  156. single trivial change.
  157. .. _flake8: https://pypi.python.org/pypi/flake8