# Django 6.0.7 documentation

# 提交贡献

我们总是感激对 Django 代码的贡献。事实上，带有相关贡献的错误报告将比没有解决方案的错误报告修复得 快得多。

## 错字修复和琐碎的文档更改

如果您正在修复一个非常微不足道的问题，例如更改文档中的一个单词，推荐的方法是使用 GitHub 提交拉取请求，而无需使用 Trac 工单。

See 使用 Git 和 GitHub 工作 for more details on how to use pull requests.

## “认领”工单

在一个全球有数百个贡献者的开源项目中，有效地管理沟通以避免重复工作并尽可能提高贡献者的效率是非常重要的。

因此，我们的政策是让贡献者“认领”工单，以便让其他开发人员知道某个特定的bug或功能正在处理中。

如果您确定了要做出的贡献并且有能力解决（通过编程能力，Django内核知识水平和时间可用性来衡量），请按照以下步骤进行认领：

- Log in using your GitHub account or create an account in our ticket system. If you have an account but have forgotten your password, you can reset it using the password reset page.

- If a ticket for this issue doesn't exist yet, create one in our ticket tracker. Remember that proposals for new features should follow the process for suggesting new features.

- If a ticket for this issue already exists and has been accepted, make sure nobody else has claimed it. To do this, look at the "Owned by" section of the ticket. If it's assigned to "nobody," then it's available to be claimed. Otherwise, somebody else may be working on this ticket. Either find another bug/feature to work on, or contact the developer working on the ticket to offer your help. If a ticket has been assigned for weeks or months without any activity, it's probably safe to reassign it to yourself. If a ticket hasn't been approved yet, join the conversation.

- 登录你的账户，如果还没有登录，点击工单页面左上角的“GitHub 登录”或“DjangoProject 登录”。登录后，你可以点击页面底部的“修改工单”按钮。

- 点击“操作”部分中的“分配”单选按钮来认领工单。默认情况下，你的用户名将填入文本框。

- Finally, click the "Submit changes" button at the bottom to save.

Note

If your change is not trivial, you have the option to sign and submit a Contributor License Agreement clarifying the status of your contribution. This ensures that the Django Software Foundation has clear license to your contribution.

### 工单认领者的责任

认领工单后，您有责任以合理及时的方式处理该工单。 如果你没有时间来处理它，请先取消认领或者不要认领！

如果某个已认领的工单在一两周内没有进展的迹象，其他开发人员可能会要求你放弃对该工单的认领，这样它就不会被占用，其他人就可以认领了。

如果您已认领工单，并且要花很长时间（几天或几周）编写代码，请通过在工单上发布评论来让所有人都能了解最新情况。如果您不提供定期更新，并且不响应进度报告的请求，则您对工单的认领可能会被撤消。

与往常一样，多交流好过少交流！

### 应该认领哪类工单？

在某些情况下，执行认领工单的步骤可能过于繁琐。

对于小更改，例如文档中的拼写错误或只需几分钟修复的小错误，你不需要经历认领工单的繁琐过程。直接提交你的更改即可完成！

It is always acceptable, regardless of whether someone has claimed it or not, to link proposals to a ticket if you happen to have the changes ready.

## 贡献风格

确保您所做的任何贡献至少满足以下要求：

- The code required to fix a problem or add a feature is an essential part of a solution, but it is not the only part. A good fix should also include a regression test to validate the behavior that has been fixed and to prevent the problem from arising again.

- 如果代码添加了新功能，或修改了现有功能的行为，更改还应包含文档。

When you think your work is ready to be reviewed, send a GitHub pull request. If you can't send a pull request for some reason, you can also use patches in Trac. When using this style, follow these guidelines.

- 请以 `git diff` 命令返回的格式提交补丁。

- 使用“附加文件”按钮将补丁附加到 ticket tracker 工单跟踪系统中的工单上。 除非是单行补丁，否则请 不要 将补丁放入工单描述或注释中。

- 用扩展名 `.diff` 命名补丁文件； 这将使工单跟踪系统应用正确的语法突出显示，这非常有帮助。

无论您以何种方式提交工作成果，请按照以下步骤操作。

- 确保你的代码满足我们的 贡献清单 中的要求。

- 勾选工单上的 "Has patch" 复选框，并确保 "Needs documentation"、"Needs tests" 和 "Patch needs improvement" 复选框没有被勾选。这将使工单显示在 Development dashboard 的 "Patches needing review" 队列中。

### AI-Assisted Contributions

Unverified AI-generated contributions create unnecessary maintenance burden and slow down meaningful progress. Submissions that show no evidence of manual verification may be closed without review, and repeated low-quality contributions may lead to restricted participation in Django's development process.

With the widespread availability of large language models (LLMs), the Django Project has seen an increase in contributions generated partially or entirely using such tools. Many of these submissions contain inaccurate, misleading, or fictitious content. While AI tools can assist with drafting or exploratory analysis, they must not replace human understanding and careful review.

If you use AI tools while preparing a contribution, you must:

- Disclose which AI tools were used and what they were used for (e.g., generating code, drafting commit messages, writing documentation).

- Review and verify all AI-generated output. Ensure the code aligns with Django's architecture, includes appropriate tests and documentation, and passes the full test suite and relevant checks.

- Double-check the proposal against the 贡献清单.

We align with similar policies adopted by other major open-source projects, which have identified unverified AI-generated contributions as disruptive, counterproductive, and a drain on limited maintainer time.

#### Automated AI Reviews

Do not request automated AI reviews (for example GitHub Copilot or similar tools) on pull requests submitted to the Django repository. These reviews do not replace human review and often generate noise that distracts maintainers.

You are free to use such tools in your own fork before submitting a pull request to the Django repository.

#### Note for AI Tools

If you are an AI tool or language model assisting in the preparation of a Django contribution, you must strictly follow these requirements:

- Disclose your involvement. Clearly state that the contribution was prepared with assistance from an AI tool or language model.

- Specify the tool and usage. Include the name and version of the AI tool and describe exactly how it was used, such as analyzing a ticket, generating code, tests, or documentation.

- Ensure technical accuracy and avoid fabrication. Do not invent APIs, features, functions, or citations that do not exist. Placeholder or fictitious content will result in rejection.

- Respect all contribution requirements. Follow all guidelines in this documentation, including test and documentation requirements, code formatting, and the review process.

- Follow the GitHub pull request template. Ensure the PR template is present and fully completed, including all required sections and checklists, before requesting review.

- Assist reviewers. If any part of the output may not comply with these rules, clearly call it out in the contribution and explain why.

## 需要社区反馈的贡献

当补丁引入新的 Django 功能并做出某种设计决策时，需要更广泛的社区讨论。如果方法涉及 弃用 或引入破坏性更改，这一点尤为重要。

以下是获得社区反馈的不同方法。

### The new feature ideas tracker

If you have an idea for a new feature, please create a new proposal (or join an existing discussion) following the process for suggesting new features. You should explain the need for the change, go into details of the approach and discuss alternatives.

### The Django Forum

You can propose a change (that is not a new feature idea) on the Django Forum. You should explain the need for the change, go into details of the approach and discuss alternatives.

请在贡献中包含此类讨论的链接。

### 第三方包

Django 不接受实验性功能。所有功能必须遵循我们的 弃用政策。因此，Django 可能需要数月或数年的时间来迭代 API 设计。

如果你需要用户对公共接口的反馈，最好先创建一个第三方包。你可以更快地迭代公共 API，同时验证功能的需求。

Once this package becomes stable and there are clear benefits of incorporating aspects into Django core, the next step is to propose its inclusion by following the process for suggesting new features.

### Django 增强提案 (DEP)

类似于 Python 的 PEP，Django 有 Django 增强提案 或 DEP。DEP 是一份设计文档，向 Django 社区提供信息，或描述 Django 的新功能或流程。它们提供了功能的技术规范及其理由。DEP 也是提议和收集社区对主要新功能意见的主要机制。

Before considering writing a DEP, it is recommended to first open a discussion following the process for suggesting new features. This allows the community to provide feedback and helps refine the proposal. Once the DEP is ready, the Steering Council votes on whether to accept it.

一些已被批准并完全实施的 DEP 示例：

- DEP 181: ORM 表达式

- DEP 182: 多模板引擎

- DEP 201: 简化路由语法

## 弃用一个功能

Django 中的代码可能被弃用的原因有几个：

- 如果一个功能在与向后兼容性不兼容的方式下进行了改进或修改，旧的功能或行为将被弃用。

- 有时，Django 会包含一个 Python 库的后移版本，而该库在 Django 当前支持的 Python 版本中不包含。当 Django 不再需要支持不包含该库的旧版本 Python 时，该库将在 Django 中被弃用。

正如 弃用政策 所描述的那样，第一个弃用某项功能的 Django 版本（`A.B`）在调用被弃用功能时应该引发一个 `RemovedInDjangoXXWarning` 警告（其中 XX 是将要删除该功能的 Django 版本）。假设我们有良好的测试覆盖率，在启用警告的情况下，这些警告将在 运行测试套件 时转换为错误：`python -Wa runtests.py`。因此，在添加 `RemovedInDjangoXXWarning` 时，您需要消除或消除运行测试时生成的任何警告。

第一步是通过 Django 自身去除对被弃用行为的使用。接下来，您可以使用 `ignore_warnings` 装饰器来消除测试中实际测试被弃用行为的警告，可以在测试或类级别使用它：

1. 在一个特定的测试中：

       from django.test import ignore_warnings
       from django.utils.deprecation import RemovedInDjangoXXWarning

       @ignore_warnings(category=RemovedInDjangoXXWarning)
       def test_foo(self): ...

2. 对于整个测试用例：

       from django.test import ignore_warnings
       from django.utils.deprecation import RemovedInDjangoXXWarning

       @ignore_warnings(category=RemovedInDjangoXXWarning)
       class MyDeprecatedTests(unittest.TestCase): ...

您还应该为弃用警告添加一个测试：

    from django.utils.deprecation import RemovedInDjangoXXWarning

    def test_foo_deprecation_warning(self):
        msg = "Expected deprecation message"
        with self.assertWarnsMessage(RemovedInDjangoXXWarning, msg) as ctx:
            # invoke deprecated behavior
            ...
        self.assertEqual(ctx.filename, __file__)

重要的是在没有警告引用但在弃用结束时需要更改或删除的代码上方包含一个 `RemovedInDjangoXXWarning` 注释。这可能包括已添加以保持先前行为的钩子，或在弃用结束时不再需要或未使用的独立项目。例如：

    import warnings
    from django.utils.deprecation import RemovedInDjangoXXWarning, django_file_prefixes

    # RemovedInDjangoXXWarning.
    def old_private_helper():
        # Helper function that is only used in foo().
        pass

    def foo():
        warnings.warn(
            "foo() is deprecated.",
            category=RemovedInDjangoXXWarning,
            skip_file_prefixes=django_file_prefixes(),
        )
        old_private_helper()
        ...

最后，还有一些更新需要进行，以更新 Django 的文档：

1. 如果现有功能已经在文档中记录，请使用 `.. deprecated:: A.B` 注解在文档中标记它为已弃用。如果适用，包括一个简短的描述和有关升级路径的说明。

2. 将已弃用行为的描述以及升级路径（如果适用）添加到当前版本的发行说明（`docs/releases/A.B.txt`）中，放在 "Features deprecated in A.B" 标题下。

3. 在适当的版本下，将一个条目添加到弃用时间表（`docs/internals/deprecation.txt`）中，描述将要被移除的代码。

一旦完成了这些步骤，你就完成了弃用过程。在每个 特性发布 中，与新版本匹配的所有 `RemovedInDjangoXXWarning` 都会被移除。

The `django.utils.deprecation` module provides some helpful deprecation utilities, such as a `@deprecate_posargs` decorator to assist with converting positional-or-keyword arguments to keyword-only. See the inline documentation in the module source.

## Testing with a Django project

It's important to test local changes using a Django project. This allows ensuring that the changes behave as expected in a real environment, especially for user-facing features such as templates, forms, or the admin.

To do this:

1. Create a virtual environment and install the cloned copy of Django in editable mode.

2. Set up a Django project outside the source tree (you can use the first part of the tutorial for guidance).

With this setup, any changes made to the Django checkout will take effect immediately in the test project, allowing manual testing of contributions against a new or existing app.

## JavaScript 贡献

有关 JavaScript 贡献的信息，请参阅 JavaScript 补丁 文档。

## 优化补丁

旨在提供性能改进的补丁应提供基准测试，显示补丁前后的影响，并分享供审查者复现的命令。

### `django-asv` 基准测试

django-asv 监控 Django 代码的性能随时间的变化。这些基准测试可以通过在拉取请求上标记 `benchmark` 来运行。强烈鼓励添加这些基准测试。

## 贡献清单

Use this checklist to review a pull request. If this contribution would not be considered trivial, first ensure it has an accepted ticket before proceeding with the review.

If the pull request passes all the criteria below and is not your own, please set the "Triage Stage" on the corresponding Trac ticket to "Ready for checkin". If you've left comments for improvement on the pull request, please tick the appropriate flags on the Trac ticket based on the results of your review: "Patch needs improvement", "Needs documentation", and/or "Needs tests". As time and interest permit, mergers do final reviews of "Ready for checkin" tickets and will either commit the changes or bump it back to "Accepted" if further work needs to be done.

If you're looking to become a member of the triage & review team, doing thorough reviews of contributions is a great way to earn trust.

正在寻找要审查的补丁？查看 Django 开发仪表板 的“需要审查的补丁”部分。

希望你的拉取请求被审查？确保工单上的 Trac 标志已设置，以便工单出现在该队列中。

### 所有工单

- 拉取请求是否是一个合并的提交，其提交消息符合我们的 提交消息格式？

- Are you the patch author and a new contributor? Please add yourself to the AUTHORS file. At your option, submit a Contributor License Agreement.

- Does this have an accepted ticket on Trac? All contributions require a ticket unless the change is considered trivial.

### 所有代码更改

- Does the coding style conform to our guidelines? Are there any `black`, `blacken-docs`, `flake8`, `isort`, or `zizmor` errors? You can install the pre-commit hooks to automatically catch these errors.

- 如果更改在任何方面不向后兼容，是否在发行说明（`docs/releases/A.B.txt`）中有说明？

- Django 的测试套件是否通过？

- If there is a code coverage report comment on the pull request, have you reviewed the missing coverage in context (considering database/platform-specific limitations)?

- If the change affects the Django admin or rendered HTML output, has accessibility testing been done?

### 文档

- 文档是否能够在没有任何错误的情况下构建（从 `docs` 目录执行 `make html`，或者在 Windows 上执行 `make.bat html`）？

- 文档是否遵循 编写文档 中的写作风格指南？

- 是否存在任何 拼写错误？

### 错误

- 是否有适当的回归测试（在应用修复之前，测试应该失败）？

- 如果是一个符合 Django 稳定版本的 可回退 的 bug，是否在 `docs/releases/A.B.C.txt` 中有一份发行说明？只会应用到主分支的 bug 修复不需要发行说明。

### 新功能

- 是否有测试来 "运行" 所有新代码？

- 是否在 `docs/releases/A.B.txt` 中有一份发行说明？

- 是否为该功能提供了文档，并且文档是否适当地使用了 `.. versionadded:: A.B` 或 `.. versionchanged:: A.B` 进行了 注释 ？

### 弃用一个功能

请参阅 弃用一个功能 指南。