通用视图¶
Wagtail 提供了若干通用视图,用于处理创建/编辑模型实例、选择器模态窗口等常见任务。为方便起见,这些视图被打包在 viewset 中。
ModelViewSet¶
ModelViewSet 类提供了列出、创建、编辑和删除模型实例的视图。例如,假设我们有如下模型:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
下面的定义(放在同一应用的 views.py 中)会生成一组用于管理 Person 实例的视图:
from wagtail.admin.viewsets.model import ModelViewSet
from .models import Person
class PersonViewSet(ModelViewSet):
model = Person
form_fields = ["first_name", "last_name"]
icon = "user"
add_to_admin_menu = True
copy_view_enabled = False
inspect_view_enabled = True
person_viewset = PersonViewSet("person") # 把 /admin/person/ 定义为该 viewset 的基础 URL
随后,在 wagtail_hooks.py 中加入以下内容,即可把这个 viewset 注册到 Wagtail 管理后台,使其在 URL /admin/person/ 下可用:
from wagtail import hooks
from .views import person_viewset
@hooks.register("register_admin_viewset")
def register_viewset():
return person_viewset
该 viewset 还可以通过覆盖其它属性和方法做进一步定制。
图标¶
你可以在 ModelViewSet 上定义 icon 属性,指定该 viewset 中各个视图使用的图标。icon 需要在Wagtail 图标库中注册。
URL 前缀与命名空间¶
可以覆盖 url_prefix 和 url_namespace 属性,为视图使用自定义的 URL 前缀和命名空间。未设置时,它们默认为模型的 model_name。
列表视图¶
可以设置 list_display 属性来指定列表视图显示的列。要定制每页显示的条目数,可以设置 list_per_page 属性。此外,ordering 属性可用于覆盖列表视图中配置的 default_ordering。
你可以通过定义 list_filter 属性并指定要过滤的字段列表,为列表视图添加过滤能力。Wagtail 底层使用 django-filter 包,该属性会作为 django-filter 的 FilterSet.Meta.fields 属性传入。这意味着你也可以传入一个把字段名映射到查询表达式列表的字典。
如果你想进一步定制过滤机制,也可以通过覆盖 filterset_class 属性来使用自定义的 wagtail.admin.filters.WagtailFilterSet 子类。如果设置了 filterset_class,list_filter 属性会被忽略。更多细节请参考 django-filter 的文档。
你可以通过设置 list_export 属性指定要导出的列,为列表视图添加导出到电子表格的能力。export_filename 属性可用于定制导出电子表格的文件名。
重新排序¶
重新排序允许内容编辑者在列表视图中通过拖放手动排列条目。当你需要一个不遵循标准排序的自定义顺序时(例如把精选内容排在前面,或按重要程度组织条目),这很有用。
要启用重新排序,先在模型上添加一个用于存储位置的整数字段,然后把它作为 viewset 的 sort_order_field 属性。列表视图中会出现一个「排序条目顺序」按钮,用于按 sort_order_field 排列列表并启用拖放界面。如果你希望自定义顺序成为列表视图的默认排序,请同时把该排序字段设为 viewset 的 ordering 属性。
下面的模型用 sort_order 字段存储排序位置。
from django.db import models
class Employee(models.Model):
full_name = models.CharField(max_length=100)
role = models.CharField(max_length=50)
# 把 sort_order 默认设为 0,以避免出现 NULL 值
sort_order = models.IntegerField(default=0, blank=True, db_index=True)
下面的 viewset 定义启用了重新排序功能,并将其作为列表的默认排序:
from wagtail.admin.viewsets.model import ModelViewSet
from .models import Employee
class EmployeeViewSet(ModelViewSet):
model = Employee
icon = "user"
add_to_admin_menu = True
form_fields = ["full_name", "role"]
list_display = ["full_name", "role"]
sort_order_field = "sort_order" # Enables the menu for drag-and-drop reordering
ordering = ["sort_order"] # Activates the drag-and-drop interface by default
employee_viewset = EmployeeViewSet("employee")
注意,排序字段应从 form_fields 中排除 —— Wagtail 会通过拖放界面自动处理它。
处理已有数据¶
使用 sort_order_field 启用拖放重新排序时,务必确保所有已有记录在该字段上都有有效且唯一的值。
如果模型中已有记录,而排序字段为空、为 null 或含有重复值,重新排序功能可能表现不可靠。这是因为每个条目都必须有互不相同的位置值,才能正确确定其顺序。
准备已有数据¶
在启用重新排序之前,应确保所有已有记录在排序字段上都被赋了连续的值。推荐的做法是使用数据迁移为已有行填充该字段。
# 数据迁移示例
from django.db import migrations, models
def populate_sort_order(apps, schema_editor):
Employee = apps.get_model("myapp", "Employee")
for i, employee in enumerate(Employee.objects.order_by("id")):
employee.sort_order = i
employee.save()
class Migration(migrations.Migration):
dependencies = [
# ...
]
operations = [
migrations.RunPython(
populate_sort_order,
migrations.RunPython.noop,
),
]
创建与编辑视图¶
你可以在 ModelViewSet 或你的 Django 模型上定义 panels 或 edit_handler 属性,以使用 Wagtail 的面板机制。更多细节见 面板。
如果既没有定义 panels 也没有 edit_handler,且没有覆盖 get_edit_handler() 方法,表单会渲染为普通的 Django 表单。你可以设置 form_fields 属性指定表单中显示的字段,来定制该表单。另外,也可以设置 exclude_form_fields 属性指定要从表单中排除的字段。如果不使用面板,你必须定义 form_fields 或 exclude_form_fields,除非覆盖了 get_form_class()。
复制视图¶
复制视图默认启用,拥有该模型「添加」权限的用户可访问它。要禁用它,请把 copy_view_enabled 设为 False。
该视图的表单会以与创建或编辑表单相同的方式生成。要使用自定义表单,请覆盖 copy_view_class 并修改该类上的 form_class 属性。
查看详情视图¶
查看详情视图默认禁用,因为对大多数模型来说它并不常用。不过,如果你需要一个能让用户查看某个实例更详细信息、但不能编辑的视图,可以在 ModelViewSet 类上设置 inspect_view_enabled 来启用它。
启用查看详情视图后,列表视图的每一行都会自动出现一个「查看详情」按钮,点击后进入一个显示该实例字段值列表的视图。
默认会显示所有「具体」字段(字段值在模型的数据库表中以列的形式存储)。这与为创建和编辑视图设置的任何 panels 或 edit_handler 定义无关。你可以通过在 ModelViewSet 类上指定 inspect_view_fields 或 inspect_view_fields_exclude 属性,定制显示哪些值。
模板¶
如果设置了 template_prefix,Wagtail 会在回退到默认模板之前,依次在你的项目或应用的下列目录中查找视图模板:
templates/{template_prefix}/{app_label}/{model_name}/templates/{template_prefix}/{app_label}/templates/{template_prefix}/
例如,要覆盖 IndexView 所用的模板,你可以新建一个 index.html 模板并把它放在上述某个位置。举例来说,假设 template_prefix 为 custom/campaign,merch 应用中有一个 Shirt 模型,你可以把自定义模板添加为 templates/custom/campaign/merch/shirt/index.html。
对于某些常用视图,Wagtail 还允许通过在 viewset 上覆盖 {view_name}_template_name 属性来覆盖所用模板。下面是各视图的定制点列表:
IndexView:index.html或index_template_name对于 AJAX 响应中使用的结果片段(例如搜索时),定制
index_results.html或index_results_template_name
CreateView:create.html或create_template_nameEditView:edit.html或edit_template_nameDeleteView:delete.html或delete_template_nameHistoryView:history.html或history_template_nameInspectView:inspect.html或inspect_template_name
其它定制¶
默认情况下,用 ModelViewSet 注册的模型也会注册到引用索引。你可以把 add_to_reference_index 设为 False 来关闭此行为。
另有多种属性可用于定制 viewset —— 见 ModelViewSet 文档。
ChooserViewSet¶
ChooserViewSet 类提供构成模态选择器界面的各个视图,让用户从模型实例列表中选择,用于填充 ForeignKey 字段。仍然使用同一个 Person 模型,下面的定义(放在 views.py 中)会生成人员选择器模态窗口的视图:
from wagtail.admin.viewsets.chooser import ChooserViewSet
class PersonChooserViewSet(ChooserViewSet):
# 模型既可以指定为模型类,也可以指定为 "app_label.model_name" 字符串;
# 使用字符串可以避免在访问 StreamField 区块类时出现循环导入(见下文)
model = "myapp.Person"
icon = "user"
choose_one_text = "Choose a person"
choose_another_text = "Choose another person"
edit_item_text = "Edit this person"
form_fields = ["first_name", "last_name"] # fields to show in the "Create" tab
person_chooser_viewset = PersonChooserViewSet("person_chooser")
同样可以用 register_admin_viewset hook 注册它:
from wagtail import hooks
from .views import person_chooser_viewset
@hooks.register("register_admin_viewset")
def register_viewset():
return person_chooser_viewset
注册选择器 viewset 还会设置一个选择器小部件,当指向该模型的 ForeignKey 字段出现在 WagtailAdminModelForm 中时就会使用它 —— 见 在管理后台视图中使用表单。特别地,这意味着像 FieldPanel("author")(其中 author 是指向 Person 模型的外键)这样的面板定义会自动使用这个选择器界面。也可以直接从 viewset 的 widget_class 属性获取选择器小部件类(例如用于普通 Django 表单)。例如,把以下代码放在 widgets.py 中,就可以通过 from myapp.widgets import PersonChooserWidget 导入该选择器小部件:
from .views import person_chooser_viewset
PersonChooserWidget = person_chooser_viewset.widget_class
该 viewset 还通过 get_block_class 方法提供 StreamField 选择器区块类。把以下代码放在 blocks.py 中,就能通过 from myapp.blocks import PersonChooserBlock 导入一个可在 StreamField 定义中使用的选择器区块:
from .views import person_chooser_viewset
PersonChooserBlock = person_chooser_viewset.get_block_class(
name="PersonChooserBlock", module_path="myapp.blocks"
)
通过关联字段限制选项¶
选择器 viewset 提供一种机制,可根据调用页面上另一个输入字段来限制选择器中显示的选项。例如,假设人员模型有一个国家字段 —— 我们就可以建立一个带国家下拉框和人员选择器的页面模型,编辑者先从下拉框选一个国家,再打开人员选择器,就会看到该国家的人员列表。
为此,请在 ChooserViewSet 上定义 url_filter_parameters 属性。它指定一组用于过滤结果的 URL 参数 —— 每当这些参数出现在 URL 中时,就会对相应的同名字段向查询集应用 filter 条件。这些参数也应列入 preserve_url_parameters 属性,以便在浏览选择器时(例如跟随分页链接)在 URL 中保留它们。下面的定义可让人员选择器按国家过滤:
class PersonChooserViewSet(ChooserViewSet):
model = "myapp.Person"
url_filter_parameters = ["country"]
preserve_url_parameters = ["multiple", "country"]
现在需要配置选择器小部件,让它在打开模态窗口时传递这些 URL 参数。这是通过向小部件构造函数传入 linked_fields 字典完成的,其中键是要传递的 URL 参数名,值是调用页面上对应输入字段的 CSS 选择器。例如,假设我们有一个带国家下拉框和人员选择器的页面模型:
class BlogPage(Page):
country = models.ForeignKey(
Country, null=True, blank=True, on_delete=models.SET_NULL
)
author = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
content_panels = Page.content_panels + [
FieldPanel("country"),
FieldPanel(
"author",
widget=PersonChooserWidget(
linked_fields={
# 把在 id_country 输入框中选择的国家传给人员选择器,
# 作为 URL 参数 `country`
"country": "#id_country",
}
),
),
]
另外还有多种查找机制可用:
PersonChooserWidget(
linked_fields={
"country": {"selector": "#id_country"} # 等价于 'country': '#id_country'
}
)
# 按 ID 查找
PersonChooserWidget(linked_fields={"country": {"id": "id_country"}})
# 用正则匹配,适用于 ID 是动态生成的 StreamField 和 InlinePanel:
# 1) 把当前小部件表单元素的 ID(即 PersonChooserWidget)
# 与正则 '^id_blog_person_relationship-\d+-' 匹配
# 2) 在匹配到的子串后面追加 'country'
# 3) 取出具有该 ID 的输入字段
PersonChooserWidget(
linked_fields={
"country": {"match": r"^id_blog_person_relationship-\d+-", "append": "country"},
}
)
面向非模型数据源的选择器 viewset¶
通用选择器视图主要设计为以 Django 模型作为数据源,但基于其它来源(例如 REST API 端点)的选择器也可以通过 queryish 库实现,该库允许把任何数据源包装成类似 Django QuerySet 的接口。然后就可以像普通模型一样把它传给 ChooserViewSet。例如,queryish 文档中的 Pokemon 示例可以做成如下选择器:
# views.py
import re
from queryish.rest import APIModel
from wagtail.admin.viewsets.chooser import ChooserViewSet
class Pokemon(APIModel):
class Meta:
base_url = "https://pokeapi.co/api/v2/pokemon/"
detail_url = "https://pokeapi.co/api/v2/pokemon/%s/"
fields = ["id", "name"]
pagination_style = "offset-limit"
verbose_name_plural = "pokemon"
@classmethod
def from_query_data(cls, data):
return cls(
id=int(
re.match(
r"https://pokeapi.co/api/v2/pokemon/(\d+)/", data["url"]
).group(1)
),
name=data["name"],
)
@classmethod
def from_individual_data(cls, data):
return cls(
id=data["id"],
name=data["name"],
)
def __str__(self):
return self.name
class PokemonChooserViewSet(ChooserViewSet):
model = Pokemon
choose_one_text = "Choose a pokemon"
choose_another_text = "Choose another pokemon"
pokemon_chooser_viewset = PokemonChooserViewSet("pokemon_chooser")
# wagtail_hooks.py
from wagtail import hooks
from .views import pokemon_chooser_viewset
@hooks.register("register_admin_viewset")
def register_pokemon_chooser_viewset():
return pokemon_chooser_viewset