编码风格

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

Pre-commit checks

pre-commit is a framework for managing pre-commit hooks. These hooks help to identify simple issues before committing code for review. By checking for these issues before code review it allows the reviewer to focus on the change itself, and it can also help to reduce the number CI runs.

To use the tool, first install pre-commit and then the git hooks:

Linux/MacOS    Windows

  1. $ python -m pip install pre-commit
  2. $ pre-commit install
  1. ...\> py -m pip install pre-commit
  2. ...\> pre-commit install

On the first commit pre-commit will install the hooks, these are installed in their own environments and will take a short while to install on the first run. Subsequent checks will be significantly faster. If the an error is found an appropriate error message will be displayed. If the error was with isort then the tool will go ahead and fix them for you. Review the changes and re-stage for commit if you are happy with them.

Python 编码风格

  • 请遵循 .editorconfig 文件中规定的缩进样式。我们建议使用带有 EditorConfig 支持的文本编辑器,以避免缩进和空格问题。 Python文件使用4个空格进行缩进,而HTML文件使用2个空格。

  • 除非另有约定的情况下,否则遵从 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.

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

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

    1. raise AttributeError(
    2. 'Here is a multiline error message '
    3. 'shortened for clarity.'
    4. )

    替换为:

    1. raise AttributeError('Here is a multiline error message '
    2. '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.

  • String variable interpolation may use %-formatting, f-strings, or str.format() as appropriate, with the goal of maximizing code readability.

    Final judgments of readability are left to the Merger’s discretion. As a guide, f-strings should use only plain variable and property access, with prior local variable assignment for more complex cases:

    1. # Allowed
    2. f'hello {user}'
    3. f'hello {user.name}'
    4. f'hello {self.user.name}'
    5. # Disallowed
    6. f'hello {get_user()}'
    7. f'you are {user.age * 365.25} days old'
    8. # Allowed with local variable assignment
    9. user = get_user()
    10. f'hello {user}'
    11. user_days_old = user.age * 365.25
    12. f'you are {user_days_old} days old'

    f-strings should not be used for any string that may require translation, including error and logging messages. In general format() is more verbose, so the other formatting methods are preferred.

    Don’t waste time doing unrelated refactoring of existing code to adjust the formatting method.

  • 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.

    Use assertIs(…, True/False) for testing boolean values, rather than assertTrue() and assertFalse(), so you can check the actual boolean value, not the truthiness of the expression.

  • 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:

    1. def test_foo():
    2. """
    3. A test docstring looks like this (#123456).
    4. """
    5. ...

导入

  • Use isort to automate import sorting using the guidelines below.

    Quick start:

    Linux/MacOS    Windows

    1. $ python -m pip install isort >= 5.1.0
    2. $ isort -rc .
    1. ...\> py -m pip install isort >= 5.1.0
    2. ...\> isort -rc .

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

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

  • On each line, alphabetize the items with the upper case items grouped before the lowercase items.

  • 使用括号和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 (

    1. Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse,
    2. cookie,

    )

    local Django

    from .models import LogEntry

    try/except

    try:

    1. import yaml

    except ImportError:

    1. yaml = None

    CONSTANT = ‘foo’

  1. class Example:
  2. # ...
  3. ```
  • 尽可能使用便利的导入,例如:这样做

    1. from django.views import View

    替换成:

    1. from django.views.generic.base import View

模版风格

  • 在Django模板代码中,在大括号和标签内容之间放置一个(只有一个)空格。

    这样做:

    1. {{ foo }}

    不要这样做:

    1. {{foo}}

视图风格

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

    这样做:

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

    别这样做:

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

模型风格

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

    这样做:

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

    别这样做:

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

    这样做:

    1. class Person(models.Model):
    2. first_name = models.CharField(max_length=20)
    3. last_name = models.CharField(max_length=40)
    4. class Meta:
    5. verbose_name_plural = 'people'

    别这样做:

    1. class Person(models.Model):
    2. first_name = models.CharField(max_length=20)
    3. last_name = models.CharField(max_length=40)
    4. class Meta:
    5. verbose_name_plural = 'people'

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

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

    • 所有数据库字段
    • 自定义管理器属性
    • Meta 类
    • `` __str__() 方法``
    • save() 方法
    • get_absolute_url() 方法
    • 其他自定义方法
  • If choices is defined for a given model field, define each choice as a list of tuples, with an all-uppercase name as a class attribute on the model. Example:

    1. class MyModel(models.Model):
    2. DIRECTION_UP = 'U'
    3. DIRECTION_DOWN = 'D'
    4. DIRECTION_CHOICES = [
    5. (DIRECTION_UP, 'Up'),
    6. (DIRECTION_DOWN, 'Down'),
    7. ]

django.conf.settings 配置的使用

通常,模块不应使用存储在顶层的配置 django.conf.settings 配置(即在导入模块时进行评估)。 对此的解释如下:

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

  1. from django.conf import settings
  2. settings.configure({}, SOME_SETTING='foo')

但是,如果在配置 settings.configure 行配置之前访问了任何设置,则此操作将无效。(在内部,settings 配置是一个 LazyObject ,当尚未访问设置时,它会自动配置自己)。

因此,如果有一个包含一些代码的模块,如下所示:

  1. from django.conf import settings
  2. from django.urls import get_callable
  3. default_foo_view = get_callable(settings.FOO_VIEW)

…然后导入此模块将导致设置对象被配置。 这意味着第三方在顶层导入模块的能力与手动配置设置对象的能力不兼容,或者在某些情况下使其变得非常困难。

为了替换上面的代码,必须使用惰性级别或间接级别,例如 django.utils.functional.LazyObjectdjango.utils.functional.lazy() 或者 lambda

杂项

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

JavaScript 样式

关于 Django 所使用 JavaScript 代码样式的更多内容,请参见 JavaScript