编码风格

当编写Django代码时,请遵从这些编码标准。

Python 编码风格

  • Please conform to the indentation style dictated in the .editorconfig file. We recommend using a text editor with EditorConfig support to avoid indentation and whitespace issues. The Python files use 4 spaces for indentation and the HTML files use 2 spaces.

  • 除非另有约定的情况下,否则遵从 PEP8 编码规范。

    Use flake8 to check for problems in this area. Note that our setup.cfg file contains some excluded files (deprecated modules we don't care about cleaning up and some third-party code that Django vendors) as well as some excluded errors that we don't consider as gross violations. Remember that PEP 8 is only a guide, so respect the style of the surrounding code as a primary goal.

    An exception to PEP 8 is our rules on line lengths. Don't limit lines of code to 79 characters if it means the code looks significantly uglier or is harder to read. We allow up to 119 characters as this is the width of GitHub code review; anything longer requires horizontal scrolling which makes review more difficult. This check is included when you run flake8. Documentation, comments, and docstrings should be wrapped at 79 characters, even though PEP 8 suggests 72.

  • 使用四个空格作为缩进。

  • 使用四个空格的悬挂缩进而不是垂直对齐。

    raise AttributeError(
        'Here is a multiline error message '
        'shortened for clarity.'
    )
    

    替换为:

    raise AttributeError('Here is a multiline error message '
                         'shortened for clarity.')
    

    这样能更好的利用空间,而且可以避免当第一行长度变化时需要重新对齐。

  • Use single quotes for strings, or a double quote if the string contains a single quote. Don't waste time doing unrelated refactoring of existing code to conform to this style.

  • Avoid use of "we" in comments, e.g. "Loop over" rather than "We loop over".

  • 在给变量,函数和方法命名时候使用下划线而不是小驼峰 (例如: poll.get_unique_voters(), not poll.getUniqueVoters() )。

  • 类名使用“大驼峰命名法”(或者是用在能返回类的工厂函数上面)。

  • 对于文档字符串,遵从现有文档字符串风格和 PEP257 规范。

  • In tests, use assertRaisesMessage() and assertWarnsMessage() instead of assertRaises() and assertWarns() so you can check the exception or warning message. Use assertRaisesRegex() and assertWarnsRegex() only if you need regular expression matching.

  • In test docstrings, state the expected behavior that each test demonstrates. Don't include preambles such as "Tests that" or "Ensures that".

    Reserve ticket references for obscure issues where the ticket has additional details that can't be easily described in docstrings or comments. Include the ticket number at the end of a sentence like this:

    def test_foo():
        """
        A test docstring looks like this (#123456).
        """
        ...
    

导入

  • 通过下面的指引使用 isort 自动给导入语句排序。

    Quick start:

    $ pip install isort
    $ isort -rc .
    
    ...\> pip install isort
    ...\> isort -rc .
    

    这将从你的当前目录递归运行 isort ,修改所有不符合指引的文件,如果你不需要排序(例如:避免循环导入)请在你的导入里面像这样加上注释:

    import module  # isort:skip
    
  • 把导入这样进行分组:future库,python标准库,第三方库, 其他的Django组件,本地Django组件,try/excepts块。按照字母顺序对每个分组进行排序,按照完整的模块名称。在每个分组里面把import module句子放在 from module importobjects句子前面。对于其他Django组件使用绝对导入,对本地Django组件使用相对导入。

  • 在每行中,大写字母的导入排在小写字母的导入之后。

  • 使用括号和4个连续空格构成的缩进去打破长行,在最后一个导入之后写一个逗号,把右括号放在单独一行。

    在最后一个导入和任何代码块之间留出一个空行,在第一个函数或类前面留出两个空行。

    例如(注释仅作为解释用途):

    django/contrib/admin/example.py
    # future
    from __future__ import unicode_literals
    
    # standard library
    import json
    from itertools import chain
    
    # third-party
    import bcrypt
    
    # Django
    from django.http import Http404
    from django.http.response import (
        Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse,
        cookie,
    )
    
    # local Django
    from .models import LogEntry
    
    # try/except
    try:
        import yaml
    except ImportError:
        yaml = None
    
    CONSTANT = 'foo'
    
    
    class Example:
        # ...
    
  • 尽可能使用便利的导入,例如:这样做

    from django.views import View
    

    替换成:

    from django.views.generic.base import View
    

模版风格

  • In Django template code, put one (and only one) space between the curly brackets and the tag contents.

    这样做:

    {{ foo }}
    

    不要这样做:

    {{foo}}
    

视图风格

  • 在Django的视图中,第一个参数应该总是 request

    这样做:

    def my_view(request, foo):
        # ...
    

    别这样做:

    def my_view(req, foo):
        # ...
    

模型风格

  • 字段名称应当全部使用小写,使用下划线替代驼峰命名。

    这样做:

    class Person(models.Model):
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=40)
    

    别这样做:

    class Person(models.Model):
        FirstName = models.CharField(max_length=20)
        Last_Name = models.CharField(max_length=40)
    
  •  class Meta 类应该位于定义字段之后,用一个空行分割字段定义和类定义。

    这样做:

    class Person(models.Model):
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=40)
    
        class Meta:
            verbose_name_plural = 'people'
    

    别这样做:

    class Person(models.Model):
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=40)
        class Meta:
            verbose_name_plural = 'people'
    

    不要这样做,也不要这样做。。。。。。

    class Person(models.Model):
        class Meta:
            verbose_name_plural = 'people'
    
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=40)
    
  • 模型内的类核方法的定义应该遵循以下顺序(不是所有项都是必须的):

    • 所有数据库字段
    • 自定义管理器属性
    • class Meta
    • def __str__()
    • def save()
    • def get_absolute_url()
    • 其他自定义方法
  • 如果模型字段定义了choices字段,那么定义的元组的名称都应该大写相当于类的属性。例如:

    class MyModel(models.Model):
        DIRECTION_UP = 'U'
        DIRECTION_DOWN = 'D'
        DIRECTION_CHOICES = (
            (DIRECTION_UP, 'Up'),
            (DIRECTION_DOWN, 'Down'),
        )
    

Use of django.conf.settings

Modules should not in general use settings stored in django.conf.settings at the top level (i.e. evaluated when the module is imported). The explanation for this is as follows:

Manual configuration of settings (i.e. not relying on the DJANGO_SETTINGS_MODULE environment variable) is allowed and possible as follows:

from django.conf import settings

settings.configure({}, SOME_SETTING='foo')

However, if any setting is accessed before the settings.configure line, this will not work. (Internally, settings is a LazyObject which configures itself automatically when the settings are accessed if it has not already been configured).

So, if there is a module containing some code as follows:

from django.conf import settings
from django.urls import get_callable

default_foo_view = get_callable(settings.FOO_VIEW)

...then importing this module will cause the settings object to be configured. That means that the ability for third parties to import the module at the top level is incompatible with the ability to configure the settings object manually, or makes it very difficult in some circumstances.

Instead of the above code, a level of laziness or indirection must be used, such as django.utils.functional.LazyObject, django.utils.functional.lazy() or lambda.

杂项

  • Mark all strings for internationalization; see the i18n documentation for details.
  • flake8将为你识别删除更改代码时不再使用的import语句,如果因为向后兼容的原因需要保留导入,则可以在导入语句后面加上# NOQA消除flake8的警告。
  • 按部就班的删除代码结尾那些增加不必要字节的空格,增加了显示混乱还可能导致偶尔的合并冲突。一些IDE可以通过配置自动删除它们,大多数版本控制工具可以在差异比较时高亮显示它们。
  • 请不要在你贡献的代码里面放入你的名字,我们的政策是把贡献者名字保存到随Django分发的AUTHORS文件里--—而不是分散在代码库里。如果你进行的不只是一次简单修改,请随意更改在你补丁中的AUTHORS文件。

JavaScript style

For details about the JavaScript code style used by Django, see JavaScript.