Django 管理文档生成器

Django 的 admindocs 应用程序从 INSTALLED_APPS 中的任何应用程序的模型、视图、模板标签和模板过滤器的 docstrings 中提取文档,并在 Django admin 中提供这些文档。

概况

要激活 admindocs,你需要执行以下操作:

  • django.contrib.admindocs 添加到你的 INSTALLED_APPS 中。

  • path('admin/doc/', include('django.contrib.admindocs.urls')) 加入到你的 urlpatterns 中。确保它被包含在 'admin/' 条目之前,这样对 /admin/doc/ 的请求就不会被后者处理。

  • 安装 docutils 0.19+ 包。

  • 可选的: 使用 admindocs 书签需要安装 django.contrib.admindocs.middleware.XViewMiddleware

一旦这些步骤完成,你就可以进入你的管理界面,点击页面右上方的“文档”链接,开始浏览文档。

文件辅助功能

下面的特殊标记可以在你的 docstrings 中使用,以方便创建超链接到其他组件。

Django 组件

reStructuredText 角色

模型

:model:`app_label.ModelName`

视图

:view:`app_label.view_name`

模板标签

:tag:`tagname`

模板过滤器

:filter:`filtername`

模板

:template:`path/to/template.html`

Each of these support custom link text with the format :role:`link text <link>`. For example, :tag:`block <built_in-block>`.

Changed in Django 5.2:

Support for custom link text was added.

模型参考

The models section of the admindocs page describes each model that the user has access to along with all the fields, properties, and methods available on it. Relationships to other models appear as hyperlinks. Descriptions are pulled from help_text attributes on fields or from docstrings on model methods.

一个具有有用文档的模型可能是这样的:

class BlogEntry(models.Model):
    """
    Stores a single blog entry, related to :model:`blog.Blog` and
    :model:`auth.User`.
    """

    slug = models.SlugField(help_text="A short label, generally used in URLs.")
    author = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True,
        null=True,
    )
    blog = models.ForeignKey(Blog, models.CASCADE)
    ...

    def publish(self):
        """Makes the blog entry live on the site."""
        ...
Changed in Django 5.2:

Access was restricted to only allow users with model view or change permissions.

视图参考

在你的网站中,每个 URL 在 admindocs 页面中都有一个单独的条目,点击给定的 URL 会显示相应的视图。你可以在视图函数 docstrings 中记录的有用内容包括:

  • 简要说明该视图的作用。

  • 视图模板中的 上下文,或可用的变量列表。

  • 用于该视图的一个或多个模板的名称。

例子:

from django.shortcuts import render

from myapp.models import MyModel


def my_view(request, slug):
    """
    Display an individual :model:`myapp.MyModel`.

    **Context**

    ``mymodel``
        An instance of :model:`myapp.MyModel`.

    **Template:**

    :template:`myapp/my_template.html`
    """
    context = {"mymodel": MyModel.objects.get(slug=slug)}
    return render(request, "myapp/my_template.html", context)

模板标签和过滤器参考

标签过滤器 admindocs 部分描述了所有 Django 自带的标签和过滤器(事实上, 内置标签参考内置过滤器参考 文档直接来自这些页面)。任何你创建的或由第三方应用添加的标签或过滤器也会出现在这些章节中。

模板参考

虽然 admindocs 并不包含记录模板本身的地方,但如果你在 docstring 中使用 :template:`path/to/template.html 语法,生成的页面会用 Django 的 模板加载器 验证模板的路径。这是个很方便的方法来检查指定的模板是否存在,并显示该模板在文件系统中的位置。

包含的书签

admindocs 页面上有一个书签:

关于本页面的文档

从任何页面跳转到生成该页面的视图文档。

使用这个书签需要安装 XViewMiddleware,并且你以一个 User 的身份登录到 Django admin,并且 is_staff 设置为 True