coding-style.txt 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. * The order of model inner classes and standard methods should be as
  86. follows (noting that these are not all required):
  87. * All database fields
  88. * Custom manager attributes
  89. * ``class Meta``
  90. * ``def __unicode__()``
  91. * ``def __str__()``
  92. * ``def save()``
  93. * ``def get_absolute_url()``
  94. * Any custom methods
  95. * If ``choices`` is defined for a given model field, define the choices as
  96. a tuple of tuples, with an all-uppercase name, either near the top of
  97. the model module or just above the model class. Example::
  98. DIRECTION_CHOICES = (
  99. ('U', 'Up'),
  100. ('D', 'Down'),
  101. )
  102. Use of ``django.conf.settings``
  103. -------------------------------
  104. Modules should not in general use settings stored in ``django.conf.settings``
  105. at the top level (i.e. evaluated when the module is imported). The explanation
  106. for this is as follows:
  107. Manual configuration of settings (i.e. not relying on the
  108. ``DJANGO_SETTINGS_MODULE`` environment variable) is allowed and possible as
  109. follows::
  110. from django.conf import settings
  111. settings.configure({}, SOME_SETTING='foo')
  112. However, if any setting is accessed before the ``settings.configure`` line,
  113. this will not work. (Internally, ``settings`` is a ``LazyObject`` which
  114. configures itself automatically when the settings are accessed if it has not
  115. already been configured).
  116. So, if there is a module containing some code as follows::
  117. from django.conf import settings
  118. from django.core.urlresolvers import get_callable
  119. default_foo_view = get_callable(settings.FOO_VIEW)
  120. ...then importing this module will cause the settings object to be configured.
  121. That means that the ability for third parties to import the module at the top
  122. level is incompatible with the ability to configure the settings object
  123. manually, or makes it very difficult in some circumstances.
  124. Instead of the above code, a level of laziness or indirection must be used,
  125. such as ``django.utils.functional.LazyObject``,
  126. ``django.utils.functional.lazy()`` or ``lambda``.
  127. Miscellaneous
  128. -------------
  129. * Mark all strings for internationalization; see the :doc:`i18n
  130. documentation </topics/i18n/index>` for details.
  131. * Remove ``import`` statements that are no longer used when you change code.
  132. The most common tools for this task are `pyflakes`_ and `pylint`_.
  133. * Systematically remove all trailing whitespaces from your code as those
  134. add unnecessary bytes, add visual clutter to the patches and can also
  135. occasionally cause unnecessary merge conflicts. Some IDE's can be
  136. configured to automatically remove them and most VCS tools can be set to
  137. highlight them in diff outputs. Note, however, that patches which only
  138. remove whitespace (or only make changes for nominal :pep:`8` conformance)
  139. are likely to be rejected, since they only introduce noise rather than
  140. code improvement. Tidy up when you're next changing code in the area.
  141. * Please don't put your name in the code you contribute. Our policy is to
  142. keep contributors' names in the ``AUTHORS`` file distributed with Django
  143. -- not scattered throughout the codebase itself. Feel free to include a
  144. change to the ``AUTHORS`` file in your patch if you make more than a
  145. single trivial change.
  146. .. _pep8: http://pypi.python.org/pypi/pep8
  147. .. _pyflakes: http://pypi.python.org/pypi/pyflakes
  148. .. _pylint: http://pypi.python.org/pypi/pylint