2
0

coding-style.txt 6.5 KB

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