模型参考¶
本文包含 wagtail.models 模块中各模型类的参考资料。
Page¶
数据库字段¶
- class wagtail.models.AbstractPage¶
- title¶
(文本)
页面的可读标题。
- draft_title¶
(文本)
页面的可读标题,会包含草稿编辑中做出的任何改动(与
title字段不同 —— 对已发布的页面,后者是当前已发布版本中存在的标题)。
- slug¶
(文本)
用于构造页面的 URL。
例如:
https://domain.com/blog/[my-slug]/
- content_type¶
(外键,指向
django.contrib.contenttypes.models.ContentType)指向
ContentType对象的外键,该对象表示该页面所属的具体模型。
- live¶
(布尔值)
当页面已发布时,该布尔值为
True。注意:该字段默认为
True,意味着任何通过程序创建的页面默认都会发布。
- has_unpublished_changes¶
(布尔值)
当页面处于草稿状态、或已发布但带草稿改动时,该布尔值为
True。
- owner¶
(外键,指向用户模型)
指向创建该页面的用户的外键。
- first_published_at¶
(日期/时间)
页面首次发布的日期/时间。
- last_published_at¶
(日期/时间)
页面最后发布的日期/时间。
- locked¶
(布尔值)
设为
True时,Wagtail 编辑器不允许任何用户编辑该页面的内容。如果同时设置了
locked_by,则只有该用户可以编辑该页面。
- locked_by¶
(外键,指向用户模型)
当前锁定该页面的用户。只有该用户可以编辑该页面。
如果
locked为True而此字段为None,则没有人能编辑该页面。
- locked_at¶
(日期/时间)
页面被锁定的日期/时间。
- alias_of¶
(外键,指向另一个页面)
若已设置,则该页面是本字段所引用页面的别名。
- locale¶
(外键,指向 Locale)
该外键链接到表示该页面语言的
Locale对象。
- translation_key¶
(uuid)
在页面的各译文之间共享的 UUID。它在创建新页面时随机生成,并在创建页面译文时被复制。
一个
translation_key值在每个区域中只能用于一个页面。
- class wagtail.models.ShowInMenusMixin¶
(布尔值)
控制该页面是否应包含在站点范围的菜单中,它显示在页面编辑器的
promote_panels里。Wagtail 默认不包含任何菜单实现,这意味着除非在具体的 Wagtail 安装中按那种方式实现,否则该字段不会对前端内容产生任何影响。
不过,
in_menu()这个 QuerySet 过滤器会用到它,以便更容易地查询使用该字段的页面。默认为
False,可以在模型上用show_in_menus_default = True覆盖。备注
要为所有页面设置全局默认值,请在首次导入
Page模型的地方设置一次Page.show_in_menus_default = True。
- class wagtail.models.DefaultBasePageMixin¶
- seo_title¶
(文本)
另行为 SEO 拟定的标题,用于页面的
<title>HTML 标签。
- search_description¶
(文本)
为 SEO 拟定的内容描述,用于搜索索引。它也适合用作页面的
<meta name="description">HTML 标签。
- class wagtail.models.Page¶
所有页面类型都继承自的标准基础页面模型,除非用 WAGTAIL_PAGE_MODEL 覆盖(见 定义自定义基础页面模型)。
方法与属性¶
除所提供的模型字段之外,Page 还有许多属性与方法,你可能想在创建自己的模型时参考、使用或覆盖它们。
备注
另见 django-treebeard 的 节点 API。Page 是物化路径树节点的子类。
- class wagtail.models.AbstractPage
- get_specific(deferred=False, copy_attrs=None, copy_attrs_exclude=None)¶
Return this object in its most specific subclassed form.
By default, a database query is made to fetch all field values for the specific object. If you only require access to custom methods or other non-field attributes on the specific object, you can use
deferred=Trueto avoid this query. However, any attempts to access specific field values from the returned object will trigger additional database queries.By default, references to all non-field attribute values are copied from current object to the returned one. This includes:
Values set by a queryset, for example: annotations, or values set as a result of using
select_related()orprefetch_related().Any
cached_propertyvalues that have been evaluated.Attributes set elsewhere in Python code.
For fine-grained control over which non-field values are copied to the returned object, you can use
copy_attrsto specify a complete list of attribute names to include. Alternatively, you can usecopy_attrs_excludeto specify a list of attribute names to exclude.If called on an object that is already an instance of the most specific class, the object will be returned as is, and no database queries or other operations will be triggered.
If the object was originally created using a model that has since been removed from the codebase, an instance of the base class will be returned (without any custom field values or other functionality present on the original class). Usually, deleting these objects is the best course of action, but there is currently no safe way for Wagtail to do that at migration time.
- specific¶
Returns this object in its most specific subclassed form with all field values fetched from the database. The result is cached in memory.
- specific_deferred¶
Returns this object in its most specific subclassed form without any additional field values being fetched from the database. The result is cached in memory.
- specific_class¶
Return the class that this object would be if instantiated in its most specific form.
If the model class can no longer be found in the codebase, and the relevant
ContentTypehas been removed by a database migration, the return value will beNone.If the model class can no longer be found in the codebase, but the relevant
ContentTypeis still present in the database (usually a result of switching between git branches without running or reverting database migrations beforehand), the return value will beNone.
- get_base_page()¶
Returns this page in "non-specific" form - that is, as an instance of the base page model that this page inherits from.
- cached_content_type¶
Return this object's
content_typevalue from theContentTypemodel's cached manager, which will avoid a database query if the content type is already in memory.
- page_type_display_name¶
A human-readable version of this page's type.
- get_url(request=None, current_site=None)¶
Return the 'most appropriate' URL for referring to this page from the pages we serve, within the Wagtail backend and actual website templates; this is the local URL (starting with '/') if we're only running a single site (i.e. we know that whatever the current page is being served from, this link will be on the same domain), and the full URL (with domain) if not. Return
Noneif the page is not routable.Accepts an optional but recommended
requestkeyword argument that, if provided, will be used to cache site-level URL information (thereby avoiding repeated database / cache lookups) and, via theSite.find_for_request()function, determine whether a relative or full URL is most appropriate.
- get_full_url(request=None)¶
Return the full URL (including protocol / domain) to this page, or
Noneif it is not routable.
- full_url¶
Return the full URL (including protocol / domain) to this page, or
Noneif it is not routable.
- relative_url(current_site, request=None)¶
Return the 'most appropriate' URL for this page taking into account the site we're currently on; a local URL if the site matches, or a fully qualified one otherwise. Return
Noneif the page is not routable.Accepts an optional but recommended
requestkeyword argument that, if provided, will be used to cache site-level URL information (thereby avoiding repeated database / cache lookups).
- get_site()¶
Return the Site object that this page belongs to.
- get_url_parts(request=None)¶
Determine the URL for this page and return it as a tuple of
(site_id, site_root_url, page_url_relative_to_site_root). ReturnNoneif the page is not routable, or return(site_id, None, None)ifNoReverseMatchexception is raised.This is used internally by the
full_url,url,relative_urlandget_siteproperties and methods; pages with custom URL routing should override this method in order to have those operations return the custom URLs.Accepts an optional keyword argument
request, which may be used to avoid repeated database / cache lookups. Typically, a page model that overridesget_url_partsshould not need to deal withrequestdirectly, and should just pass it to the original method when callingsuper.
- route(request, path_components)¶
- serve(request, *args, **kwargs)¶
- static route_for_request(request: HttpRequest, path: str) RouteResult | None¶
Find the page route for the given HTTP request object, and URL path. The route result (page, args, and kwargs) will be cached via
request._wagtail_route_for_request.
- classmethod find_for_request(request: HttpRequest, path: str) AbstractPage | None¶
Find the page for the given HTTP request object, and URL path. The full page route will be cached via
request._wagtail_route_for_request.
- get_default_privacy_setting(request)¶
设置该页面的默认隐私设置。
该方法必须返回一个至少包含 'type' 键的字典。其值必须是
PageViewRestriction的restriction_type中下列取值之一:BaseViewRestriction.NONE:页面是公开的,任何人都可以访问。(默认)- '{"type": BaseViewRestriction.NONE}'BaseViewRestriction.LOGIN:页面是私有的,只有已认证用户才能访问。- '{"type": BaseViewRestriction.LOGIN}'BaseViewRestriction.PASSWORD:页面是私有的,只有持有共享密码的用户才能访问。(需要在字典中额外提供password键)- '{"type": BaseViewRestriction.PASSWORD, "password": "P@ssw0rd123!"}'BaseViewRestriction.GROUPS:页面是私有的,只有特定用户组中的用户才能访问。(需要额外提供groups键,其值为 Group 对象列表)- '{"type": BaseViewRestriction.GROUPS, "groups": [moderators, editors]}'
示例
class BreadsIndexPage(Page): #... def get_default_privacy_setting(request): from wagtail.models import BaseViewRestriction # 如果编辑者拥有 foo.add_bar 权限,则把默认值设为勾选 moderators 与 editors 两个组的用户组限制 if request.user.has_perm("foo.add_bar"): moderators = Group.objects.filter(name="Moderators").first() editors = Group.objects.filter(name="Editors").first() return {"type": BaseViewRestriction.GROUPS, "groups": [moderators,editors]} else: return {"type": BaseViewRestriction.NONE}
- context_object_name = None¶
页面
Context中页面实例的自定义名称。
- get_context(request, *args, **kwargs)¶
- get_template(request, *args, **kwargs)¶
- get_admin_display_title()¶
Return the title for this page as it should appear in the admin backend; override this if you wish to display extra contextual information about the page, such as language. By default, returns
draft_title.
- allowed_http_methods = [<HTTPMethod.DELETE>, <HTTPMethod.GET>, <HTTPMethod.HEAD>, <HTTPMethod.OPTIONS>, <HTTPMethod.PATCH>, <HTTPMethod.POST>, <HTTPMethod.PUT>]¶
定制该属性时,建议开发者使用 Python 内置
http.HTTPMethod枚举中的值,因为它更稳健,并且使用的是内存中已有的值。例如:from http import HTTPMethod class MyPage(Page): allowed_http_methods = [HTTPMethod.GET, HTTPMethod.OPTIONS]
http.HTTPMethod枚举直到 Python 3.11 才加入,因此如果你的项目使用更早版本的 Python,可以改用大写字符串。例如:class MyPage(Page): allowed_http_methods = ["GET", "OPTIONS"]
- check_request_method(request, *args, **kwargs)¶
Checks the
methodattribute of the request against those supported by the page (as defined byallowed_http_methods) and responds accordingly.If supported,
Noneis returned, and the request is processed normally. If not, a warning is logged and anHttpResponseNotAllowedis returned, and any further request handling is terminated.
- handle_options_request(request, *args, **kwargs)¶
Returns an
HttpResponsewith an"Allow"header containing the list of supported HTTP methods for this page. This method is used instead ofserve()to handle requests when theOPTIONSHTTP verb is detected (andHTTPMethod.OPTIONSis present inallowed_http_methodsfor this type of page).
- response_media_types = ['text/html']¶
该页面类型的实例可以响应的媒体类型,例如
["text/html", "text/markdown"]。第一项是默认值。当有多项时,get_response_media_type()会依据每个请求的Accept头为其挑选一项,并把Accept加入响应的Vary头。见 如何让页面响应有所不同。
- get_response_media_type(request)¶
Returns the item of
response_media_typesthat best matches the request'sAcceptheader.The first item of
response_media_typesis returned when the client has no preference between the available types (for example,Accept: */*or noAcceptheader), or accepts none of them.
- get_vary_headers(request)¶
Returns the names of the request headers that this page's responses may depend on. Wagtail adds them to the
Varyheader of the response, so that caches store a separate response for each variant.By default, this includes
X-Requested-Withwhen the page has anajax_template, andAcceptwhen the page has more than one item inresponse_media_types.
- preview_modes¶
A list of
(internal_name, display_name)tuples for the modes in which this object can be displayed for preview/moderation purposes. Ordinarily an object will only have one display mode, but subclasses can override this - for example, a page containing a form might have a default view of the form, and a post-submission 'thank you' page. Set to[]to completely disable previewing for this model.
- default_preview_mode¶
The default preview mode to use in live preview. This default is also used in areas that do not give the user the option of selecting a mode explicitly, e.g. in the moderator approval workflow. If
preview_modesis empty, anIndexErrorwill be raised.
- preview_sizes¶
A list of dictionaries, each representing a preview size option for this object. Override this property to customize the preview sizes. Each dictionary in the list should include the following keys:
name: A string representing the internal name of the preview size.icon: A string specifying the icon's name for the preview size button.device_width: An integer indicating the device's width in pixels.label: A string for the aria label on the preview size button.
@property def preview_sizes(self): return [ { "name": "mobile", "icon": "mobile-icon", "device_width": 320, "label": "Preview in mobile size" }, # Add more preview size dictionaries as needed. ]
- default_preview_size¶
The default preview size name to use in live preview. Defaults to
"mobile", which is the first one defined inpreview_sizes. Ifpreview_sizesis empty, anIndexErrorwill be raised.
- serve_preview(request, mode_name)¶
Returns an HTTP response for use in object previews.
This method can be overridden to implement custom rendering and/or routing logic.
Any templates rendered during this process should use the
requestobject passed here - this ensures thatrequest.userand other properties are set appropriately for the wagtail user bar to be displayed/hidden. This request will always be a GET.
- get_parent(update=False)¶
- 返回:
the parent node of the current node object. Caches the result in the object itself to help in loops.
- get_children()¶
- 返回:
A queryset of all the node's children
- get_ancestors(inclusive=False)¶
Returns a queryset of the current page's ancestors, starting at the root page and descending to the parent, or to the current page itself if
inclusiveis true.
- get_descendants(inclusive=False)¶
Returns a queryset of all pages underneath the current page, any number of levels deep. If
inclusiveis true, the current page itself is included in the queryset.
- get_siblings(inclusive=True)¶
Returns a queryset of all other pages with the same parent as the current page. If
inclusiveis true, the current page itself is included in the queryset.
- get_translations(inclusive=False)¶
Returns a queryset containing the translations of this instance.
- get_translation(locale)¶
Finds the translation in the specified locale.
If there is no translation in that locale, this raises a
model.DoesNotExistexception.
- get_translation_or_none(locale)¶
Finds the translation in the specified locale.
If there is no translation in that locale, this returns
None.
- has_translation(locale)¶
Returns True if a translation exists in the specified locale.
- copy_for_translation(locale, copy_parents=False, alias=False, exclude_fields=None)¶
Creates a copy of this page in the specified locale.
- get_admin_default_ordering()¶
返回在管理后台页面索引中查看子页面、且未处于搜索结果状态时,子页面默认的排序方式。
可用的排序方式有:
'content_type''-content_type''latest_revision_created_at''-latest_revision_created_at''live''-live''ord''title''-title'
例如,让某页面的所有子页面仅在数量小于 20 个时按标题排序。
class BreadsIndexPage(Page): def get_admin_default_ordering(self): if Page.objects.child_of(self).count() < 20: return 'title' return self.admin_default_ordering
- admin_default_ordering¶
方法
get_admin_default_ordering()对应的属性版本,默认为'-latest_revision_created_at'。
- localized¶
Finds the translation in the current active language.
If there is no translation in the active language, self is returned.
Note: This will not return the translation if it is in draft. If you want to include drafts, use the
.localized_draftattribute instead.
- localized_draft¶
Finds the translation in the current active language.
If there is no translation in the active language, self is returned.
Note: This will return translations that are in draft. If you want to exclude these, use the
.localizedattribute.
- subpage_types¶
可以作为该页面类型子页面创建的页面模型列表。例如,
BlogIndex页面可以允许BlogPage作为子页面,但不允许JobPage:class BlogIndex(Page): subpage_types = ['mysite.BlogPage', 'mysite.BlogArchivePage']
把某个页面的 subpage_types 属性设为空数组,可以完全禁止为它创建子页面:
class BlogPage(Page): subpage_types = []
- parent_page_types¶
允许作为父页面的页面模型列表。例如,
BlogPage可能只允许自己在BlogIndex页面下创建:class BlogPage(Page): parent_page_types = ['mysite.BlogIndexPage']
把 parent_page_types 设为空数组,页面就可以完全禁止自己被创建(这对于创建只应存在一次的唯一页面很有用):
class HiddenPage(Page): parent_page_types = []
要让页面只能创建在根页面之下(例如针对
HomePage模型),把parent_page_type设为['wagtailcore.Page']。class HomePage(Page): parent_page_types = ['wagtailcore.Page']
- classmethod can_exist_under(parent)¶
Checks if this page type can exist as a subpage under a parent page instance.
See also:
AbstractPage.can_create_at()andAbstractPage.can_move_to()
- classmethod can_create_at(parent)¶
Checks if this page type can be created as a subpage under a parent page instance.
- can_move_to(parent)¶
Checks if this page instance can be moved to be a subpage of a parent page instance.
- get_route_paths()¶
Returns a list of paths that this page can be viewed at.
These values are combined with the dynamic portion of the page URL to automatically create redirects when the page's URL changes.
备注
If using
RoutablePageMixin, you may want to override this method to include the paths of popular routes.备注
Redirect paths are 'normalized' to apply consistent ordering to GET parameters, so you don't need to include every variation. Fragment identifiers are discarded too, so should be avoided.
- password_required_template¶
定义使用该模型的受保护页面在渲染登录表单时应使用哪个模板文件。这会覆盖你在设置中用
WAGTAIL_PASSWORD_REQUIRED_TEMPLATE定义的默认值。见 私有页面
- max_count¶
控制通过 Wagtail 管理界面可以创建该类型页面的最大数量。当需要「这类页面最多只允许存在 3 个」、或需要单例页面时,这很有用。
- max_count_per_parent¶
控制该类型页面在任意单个父页面下可以创建的最大数量。
- private_page_options¶
控制该页面类型可用的隐私选项。
可用的选项有:
'password'- 可限制为使用共享密码'groups'- 可限制为特定用户组中的用户'login'- 可限制为已登录用户class BreadPage(Page): ... # 默认 private_page_options = ['password', 'groups', 'login'] # 禁用共享密码 private_page_options = ['groups', 'login'] # 只用共享密码 private_page_options = ['password'] # 该页面模型没有任何隐私选项 private_page_options = []
- exclude_fields_in_copy¶
复制 Page 时不会被包含的字段名数组。 当你有些不使用
ClusterableModel、或不应被复制的关系时很有用。class BlogPage(Page): exclude_fields_in_copy = ['special_relation', 'custom_uuid']
以下字段在复制时始终会被排除 - ['id', 'path', 'depth', 'numchild', 'url_path', 'path']。
- base_form_class¶
该表单类被用作在 Wagtail 页面编辑器中编辑该类型页面的基础。 可以在模型上设置该属性以定制页面编辑器表单。 表单必须是
WagtailAdminPageForm的子类。 更多信息见 定制生成的表单。
- with_content_json(content)¶
Returns a new version of the page with field values updated to reflect changes in the provided
content(which usually comes from a previously-saved page revision).Certain field values are preserved in order to prevent errors if the returned page is saved, such as
id,content_typeand some tree-related values. The following field values are also preserved, as they are considered to be meaningful to the page as a whole, rather than to a specific revision:draft_titlelivehas_unpublished_changesownerlockedlocked_bylocked_atlatest_revisionlatest_revision_created_atfirst_published_atalias_ofwagtail_admin_comments(COMMENTS_RELATION_NAME)
- save(clean=True, user=None, log_action=False, **kwargs)¶
Writes the page to the database, performing additional housekeeping tasks to ensure data integrity:
locale,draft_titleandslugare set to default values if not provided, withslugbeing generated from the title with a suffix to ensure uniqueness within the parent page where necessaryThe
url_pathfield is set based on theslugand the parent pageIf the
slughas changed, theurl_pathof this page and all descendants is updated and a page_slug_changed signal is sent
New pages should be saved by passing the unsaved page instance to the
add_child()oradd_sibling()method of an existing page, which will correctly update the fields responsible for tracking the page's location in the tree.If
clean=Falseis passed, the page is saved without validation. This is appropriate for updates that only change metadata such as latest_revision while keeping content and page location unchanged.If
clean=Trueis passed (the default), and the page haslive=Trueset, the page is validated usingfull_clean()before saving.If
clean=Trueis passed, and the page haslive=Falseset, only the title and slug fields are validated.
- copy(recursive=False, to=None, update_attrs=None, copy_revisions=True, keep_live=True, user=None, process_child_object=None, exclude_fields=None, log_action='wagtail.copy', reset_translation_key=True)¶
Copies a given page
- 参数:
log_action -- flag for logging the action. Pass None to skip logging. Can be passed an action string. Defaults to
'wagtail.copy'.
- move(new_parent, pos=None)¶
把页面及其所有后代移动到一个新的父页面下。 更多信息见
django-treebeard。
- create_alias(*, recursive=False, parent=None, update_slug=None, update_locale=None, user=None, log_action='wagtail.create_alias', reset_translation_key=True, _mpnode_attrs=None)¶
- update_aliases(*, revision=None, _content=None, _updated_ids=None)¶
Publishes all aliases that follow this page with the latest content from this page.
This is called by Wagtail whenever a page with aliases is published.
- 参数:
revision (Revision, Optional) -- The revision of the original page that we are updating to (used for logging purposes)
- get_cache_key_components()¶
The components of a
Pagewhich make up thecache_key. Any change to a page should be reflected in a change to at least one of these components.
- cache_key¶
A generic cache key to identify a page in its current state. Should the page change, so will the key.
Customizations to the cache key should be made in
get_cache_key_components.
Site¶
Site 模型对多站点安装很有用,它让管理员可以配置服务器响应的每个主机名该使用页面树的哪一部分。
find_for_request() 函数返回将处理给定 HTTP 请求的 Site 对象。
数据库字段¶
方法与属性¶
- class wagtail.models.Site
- static find_for_request(request)¶
Find the site object responsible for responding to this HTTP request object. Try:
unique hostname first
then hostname and port
if there is no matching hostname at all, or no matching hostname:port combination, fall back to the unique default site, or raise an exception
NB this means that high-numbered ports on an extant hostname may still be routed to a different hostname which is set as the default
The site will be cached via request._wagtail_site
- root_url¶
返回站点的 URL。它由
hostname与port字段计算得出。URL 的协议部分依据
port字段的值计算:80 =
http://443 =
https://其它值都会使用
http://协议,端口会追加到主机名末尾(例如http://mysite.com:8000/)
- static get_site_root_paths()¶
Return a list of SiteRootPath instances, most specific path first - used to translate url_paths into actual URLs with hostnames.
Each root path is an instance of the SiteRootPath named tuple, and have the following attributes:
site_id- The ID of the Site recordroot_path- The internal URL path of the site's home page (for example '/home/')root_url- The scheme/domain name of the site (for example 'https://www.example.com/')language_code- The language code of the site (for example 'en')
Locale¶
Locale 模型定义站点上可用的语言和/或区域集合。
每条 Locale 记录都对应 WAGTAIL_CONTENT_LANGUAGES 设置中定义的一个「语言代码」。
Wagtail 最初会建立一个 Locale 作为所有既有内容的默认语言。
这第一个区域会自动从 WAGTAIL_CONTENT_LANGUAGES 中选择与 LANGUAGE_CODE 中所定义的站点主要语言代码最接近的值。
如果之后改动了主要语言代码,Wagtail 不会自动创建新的 Locale 记录,也不会更新已有的记录。
在启用国际化之前,所有页面都使用这个主 Locale 记录。
这样做是为了满足数据库约束,也让日后开启国际化更容易。
更改 WAGTAIL_CONTENT_LANGUAGES¶
可以随时间推移在 WAGTAIL_CONTENT_LANGUAGES 中增删语言。
在从 WAGTAIL_CONTENT_LANGUAGES 中移除某个选项之前,重要的是把对应的 Locale
记录更新为使用另一种内容语言,或者删除它。
任何内容语言无效的 Locale 实例都会被自动从所有数据库查询中过滤掉,使其无法被编辑或查看。
方法与属性¶
- class wagtail.models.Locale¶
- language_code¶
The language code that represents this locale
The language code can either be a language code on its own (such as
en,fr), or it can include a region code (such asen-gb,fr-fr).
- classmethod get_default()¶
Returns the default Locale based on the site's
LANGUAGE_CODEsetting.
- classmethod get_active()¶
Returns the Locale that corresponds to the currently activated language in Django.
- language_name¶
Uses data from
django.conf.localeto return the language name in English. For example, if the object'slanguage_codewere"fr", the return value would be"French".Raises
KeyErrorifdjango.conf.localehas no information for the object'slanguage_codevalue.
- language_name_local¶
Uses data from
django.conf.localeto return the language name in the language itself. For example, if thelanguage_codewere"fr"(French), the return value would be"français".Raises
KeyErrorifdjango.conf.localehas no information for the object'slanguage_codevalue.
- language_name_localized¶
Uses data from
django.conf.localeto return the language name in the currently active language. For example, iflanguage_codewere"fr"(French), and the active language were"da"(Danish), the return value would be"Fransk".Raises
KeyErrorifdjango.conf.localehas no information for the object'slanguage_codevalue.
- is_default¶
Returns a boolean indicating whether this object is the default locale.
- is_active¶
Returns a boolean indicating whether this object is the currently active locale.
- is_bidi¶
Returns a boolean indicating whether the language is bi-directional.
TranslatableMixin¶
TranslatableMixin 是一个抽象模型,可以加到任何非页面的 Django 模型上,使其可翻译。
页面已经包含该 mixin,因此无需再加。
非页面模型若要在管理后台中可翻译,还必须注册为 Snippet。另见 可翻译的 Snippet。
数据库字段¶
- class wagtail.models.TranslatableMixin¶
- locale¶
(外键,指向
wagtail.models.Locale)对页面而言,它默认为父页面的区域。
- translation_key¶
(uuid)
每当创建新的模型实例时随机生成的 UUID。 它与该实例的所有译文共享,因此可用于查询译文。
translation_key 与 locale 两个字段有唯一键约束,以防止该对象被多次翻译到同一语言。
备注
目前这一点是通过 TranslatableMixin.Meta 中的 unique_together 强制实现的,但将来可能会替换为 TranslatableMixin.Meta.constraints 中的 UniqueConstraint。
如果你的模型定义了 Meta 类(无论是新定义,还是显式继承 TranslatableMixin.Meta),在设置 unique_together 或 constraints 时要留意。确保在 translation_key 与 locale 上要么有 unique_together、要么有 UniqueConstraint(不要两者都有)。对此有一项系统检查。
方法与属性¶
- class wagtail.models.TranslatableMixin
- get_translations(inclusive=False)¶
Returns a queryset containing the translations of this instance.
- get_translation(locale)¶
Finds the translation in the specified locale.
If there is no translation in that locale, this raises a
model.DoesNotExistexception.
- get_translation_or_none(locale)¶
Finds the translation in the specified locale.
If there is no translation in that locale, this returns
None.
- has_translation(locale)¶
Returns True if a translation exists in the specified locale.
- copy_for_translation(locale, exclude_fields=None)¶
Creates a copy of this instance with the specified locale.
Note that the copy is initially unsaved.
- classmethod get_translation_model()¶
Returns this model's "Translation model".
The "Translation model" is the model that has the
localeandtranslation_keyfields. Typically this would be the current model, but it may be a super-class if multi-table inheritance is in use (as is the case forwagtailcore.Page).
- localized¶
Finds the translation in the current active language.
If there is no translation in the active language, self is returned.
Note: This will not return the translation if it is in draft. If you want to include drafts, use the
.localized_draftattribute instead.
PreviewableMixin¶
PreviewableMixin 是一个 mixin 类,可以加到任何非页面的 Django 模型上,以允许预览其实例。
页面已经包含该 mixin,因此无需再加。
非页面模型若要在管理后台中可预览,还必须注册为 Snippet。另见 让 snippet 可预览。
方法与属性¶
- class wagtail.models.PreviewableMixin¶
- preview_modes¶
A list of
(internal_name, display_name)tuples for the modes in which this object can be displayed for preview/moderation purposes. Ordinarily an object will only have one display mode, but subclasses can override this - for example, a page containing a form might have a default view of the form, and a post-submission 'thank you' page. Set to[]to completely disable previewing for this model.
- default_preview_mode¶
The default preview mode to use in live preview. This default is also used in areas that do not give the user the option of selecting a mode explicitly, e.g. in the moderator approval workflow. If
preview_modesis empty, anIndexErrorwill be raised.
- preview_sizes¶
A list of dictionaries, each representing a preview size option for this object. Override this property to customize the preview sizes. Each dictionary in the list should include the following keys:
name: A string representing the internal name of the preview size.icon: A string specifying the icon's name for the preview size button.device_width: An integer indicating the device's width in pixels.label: A string for the aria label on the preview size button.
@property def preview_sizes(self): return [ { "name": "mobile", "icon": "mobile-icon", "device_width": 320, "label": "Preview in mobile size" }, # Add more preview size dictionaries as needed. ]
- default_preview_size¶
The default preview size name to use in live preview. Defaults to
"mobile", which is the first one defined inpreview_sizes. Ifpreview_sizesis empty, anIndexErrorwill be raised.
- is_previewable()¶
Returns
Trueif at least one preview mode is specified inpreview_modes.
- get_preview_context(request, mode_name)¶
Returns a context dictionary for use in templates for previewing this object.
By default, this returns a dictionary containing the
requestand and theobjectitself.
- get_preview_template(request, mode_name)¶
Returns a template to be used when previewing this object.
Subclasses of
PreviewableMixinmust override this method to return the template name to be used in the preview. Alternatively, subclasses can also override theserve_previewmethod to completely customise the preview rendering logic.
- serve_preview(request, mode_name)¶
Returns an HTTP response for use in object previews.
This method can be overridden to implement custom rendering and/or routing logic.
Any templates rendered during this process should use the
requestobject passed here - this ensures thatrequest.userand other properties are set appropriately for the wagtail user bar to be displayed/hidden. This request will always be a GET.
RevisionMixin¶
RevisionMixin 是一个抽象模型,可以加到任何非页面的 Django 模型上,以允许保存其实例的修订版本。
页面已经包含该 mixin,因此无需再加。
非页面模型若要在管理后台中可保存修订版本,还必须注册为 Snippet。另见 保存 snippet 的修订版本。
数据库字段¶
方法与属性¶
- class wagtail.models.RevisionMixin
- _revisions¶
A default
GenericRelationfor the purpose of automatically deleting revisions when the object is deleted. This is not used to query the object's revisions. Instead, therevisions()property is used for that purpose. As such, this default relation is considered private.This
GenericRelationdoes not have arelated_query_name, so it cannot be used for reverse-related queries fromRevisionback to this model. If the feature is desired, subclasses can define their ownGenericRelationtoRevisionwith a customrelated_query_name.
- revisions¶
Returns revisions that belong to the object. For non-page models, this is done by querying the
Revisionmodel directly rather than using aGenericRelation, to avoid a known limitation in Django for models with multi-table inheritance where the relation's content type may not match the instance's type.
- save_revision(user=None, approved_go_live_at=None, changed=True, log_action=False, previous_revision=None, clean=True, overwrite_revision=None)¶
Creates and saves a revision.
- 参数:
user -- The user performing the action.
approved_go_live_at -- The date and time the revision is approved to go live.
changed -- Indicates whether there were any content changes.
log_action -- Flag for logging the action. Pass
Trueto also create a log entry. Can be passed an action string. Defaults to"wagtail.edit"when noprevious_revisionparam is passed, otherwise"wagtail.revert".previous_revision (Revision) -- Indicates a revision reversal. Should be set to the previous revision instance.
clean -- Set this to
Falseto skip cleaning object content before saving this revision.
- 返回:
The newly created revision.
- get_latest_revision_as_object()¶
Returns the latest revision of the object as an instance of the model. If no latest revision exists, returns the object itself.
- with_content_json(content)¶
Returns a new version of the object with field values updated to reflect changes in the provided
content(which usually comes from a previously-saved revision).Certain field values are preserved in order to prevent errors if the returned object is saved, such as
id. The following field values are also preserved, as they are considered to be meaningful to the object as a whole, rather than to a specific revision:latest_revision
If
TranslatableMixinis applied, the following field values are also preserved:translation_keylocale
DraftStateMixin¶
DraftStateMixin 是一个抽象模型,可以加到任何非页面的 Django 模型上,以允许其实例拥有未发布的改动。
该 mixin 要求同时应用 RevisionMixin。页面已经包含该 mixin,因此无需再加。
非页面模型若要在管理后台中拥有发布相关功能,还必须注册为 Snippet。另见 保存 snippet 的草稿改动。
数据库字段¶
方法与属性¶
- class wagtail.models.DraftStateMixin
- publish(revision, user=None, changed=True, log_action=True, previous_revision=None, skip_permission_checks=False)¶
Publish a revision of the object by applying the changes in the revision to the live object.
- 参数:
revision (Revision) -- Revision to publish.
user -- The publishing user.
changed -- Indicated whether content has changed.
log_action -- Flag for the logging action, pass
Falseto skip logging.previous_revision (Revision) -- Indicates a revision reversal. Should be set to the previous revision instance.
- unpublish(set_expired=False, commit=True, user=None, log_action=True)¶
Unpublish the live object.
- 参数:
set_expired -- Mark the object as expired.
commit -- Commit the changes to the database.
user -- The unpublishing user.
log_action -- Flag for the logging action, pass
Falseto skip logging.
- with_content_json(content)¶
Similar to
RevisionMixin.with_content_json(), but with the following fields also preserved:livehas_unpublished_changesfirst_published_at
LockableMixin¶
LockableMixin 是一个抽象模型,可以加到任何非页面的 Django 模型上,以允许其实例被锁定。
页面已经包含该 mixin,因此无需再加。更多细节见 锁定 snippet。
非页面模型若要在管理后台中可锁定,还必须注册为 Snippet。另见 锁定 snippet。
数据库字段¶
方法与属性¶
- class wagtail.models.LockableMixin
- get_lock()¶
Returns a sub-class of
BaseLockif the instance is locked, otherwiseNone.
- with_content_json(content)¶
Similar to
RevisionMixin.with_content_json(), but with the following fields also preserved:lockedlocked_atlocked_by
WorkflowMixin¶
WorkflowMixin 是一个 mixin 类,可以加到任何非页面的 Django 模型上,以允许其实例被提交到工作流。
该 mixin 要求同时应用 RevisionMixin 与 DraftStateMixin。页面已经包含该 mixin,因此无需再加。更多细节见 为 snippet 启用工作流。
非页面模型若要在管理后台中拥有工作流功能,还必须注册为 Snippet。另见 为 snippet 启用工作流。
方法与属性¶
- class wagtail.models.WorkflowMixin¶
- classmethod get_default_workflow()¶
Returns the active workflow assigned to the model.
For non-
Pagemodels, workflows are assigned to the model's content type, thus shared across all instances instead of being assigned to individual instances (unlessget_workflow()is overridden).This method is used to determine the workflow to use when creating new instances of the model. On
Pagemodels, this method is unused as the workflow can be determined from the parent page's workflow.
- has_workflow¶
Returns
`True`if the object has an active workflow assigned, otherwise`False`.
- get_workflow()¶
Returns the active workflow assigned to the object.
- _workflow_states¶
A default
GenericRelationfor the purpose of automatically deleting workflow states when the object is deleted. This is not used to query the object's workflow states. Instead, theworkflow_states()property is used for that purpose. As such, this default relation is considered private.This
GenericRelationdoes not have arelated_query_name, so it cannot be used for reverse-related queries fromWorkflowStateback to this model. If the feature is desired, subclasses can define their ownGenericRelationtoWorkflowStatewith a customrelated_query_name.
- workflow_states¶
Returns workflow states that belong to the object. For non-page models, this is done by querying the
WorkflowStatemodel directly rather than using aGenericRelation, to avoid a known limitation in Django for models with multi-table inheritance where the relation's content type may not match the instance's type.
- workflow_in_progress¶
Returns
`True`if a workflow is in progress on the current object, otherwise`False`.
- current_workflow_state¶
Returns the in progress or needs changes workflow state on this object, if it exists.
- current_workflow_task_state¶
Returns (specific class of) the current task state of the workflow on this object, if it exists.
- current_workflow_task¶
Returns (specific class of) the current task in progress on this object, if it exists.
Revision¶
每次编辑页面都会创建一个新的 Revision 并保存到数据库。它可用于查找页面所做全部改动的完整历史,也为新改动在上线之前提供了一个存放之处。
可以从任何
RevisionMixin实例调用其save_revision()方法来创建修订版本。页面内容可 JSON 序列化,存储在
content字段中。你可以通过调用
as_object()方法,把Revision取为该对象模型的一个实例。
你可以使用 purge_revisions 命令删除不再使用的旧修订版本。
数据库字段¶
- class wagtail.models.Revision¶
- content_object¶
(通用外键)
该修订版本所属的对象。对页面修订版本而言,该对象是具体页面类的实例。
- content_type¶
(外键,指向
ContentType)该修订版本所属对象的内容类型。对页面修订版本而言,指具体页面类型的内容类型。
- base_content_type¶
(外键,指向
ContentType)该修订版本所属对象的基础内容类型。对页面修订版本而言,指
Page模型的内容类型。
- object_id¶
(字符串)
该修订版本所属对象的主键。
- created_at¶
(日期/时间)
创建该修订版本的时间。
- user¶
(外键,指向用户模型)
创建该修订版本的用户。
- content¶
(字典)
创建该修订版本时对象所对应的 JSON 内容。
管理器¶
方法与属性¶
GroupPagePermission¶
数据库字段¶
PageViewRestriction¶
数据库字段¶
Orderable(抽象)¶
数据库字段¶
Workflow¶
工作流表示一系列任务,必须全部通过后才能对某个对象执行某项操作 —— 通常是发布。
数据库字段¶
方法与属性¶
- class wagtail.models.Workflow
- start(obj, user)¶
Initiates a workflow by creating an instance of
WorkflowState.
- tasks¶
Returns all
Taskinstances linked to this workflow.
- deactivate(user=None)¶
Sets the workflow as inactive, and cancels all in progress instances of
WorkflowStatelinked to this workflow.
- all_pages()¶
Returns a queryset of all the pages that this Workflow applies to.
WorkflowState¶
工作流状态表示某个已在对象上启动的工作流的状况。
数据库字段¶
- class wagtail.models.WorkflowState¶
- content_object¶
(通用外键)
已在其上启动工作流的对象。对页面工作流而言,该对象是基础
Page模型的实例。
- content_type¶
(外键,指向
ContentType)该工作流状态所属对象的内容类型。对页面工作流而言,指具体页面类型的内容类型。
- base_content_type¶
(外键,指向
ContentType)该工作流状态所属对象的基础内容类型。对页面工作流而言,指
Page模型的内容类型。
- object_id¶
(字符串)
该修订版本所属对象的主键。
- workflow¶
(外键,指向
Workflow)该
WorkflowState所表示其状态的工作流。
- status¶
(文本)
工作流的当前状态(可选值见
WorkflowState.STATUS_CHOICES)
- created_at¶
(日期/时间)
该
WorkflowState实例创建的时间 —— 即工作流启动的时间
- requested_by¶
(外键,指向用户模型)
启动该工作流的用户
- current_task_state¶
(外键,指向
TaskState)工作流当前所处任务对应的
TaskState模型:若正在进行,则是正在完成的任务状态;若已结束,则是最终任务状态
方法与属性¶
- class wagtail.models.WorkflowState
- STATUS_CHOICES¶
status字段可能取值及其可读名称组成的元组。可选值为STATUS_IN_PROGRESS、STATUS_APPROVED、STATUS_CANCELLED和STATUS_NEEDS_CHANGES。
- update(user=None, next_task=None)¶
Checks the status of the current task, and progresses (or ends) the workflow if appropriate. If the workflow progresses, next_task will be used to start a specific task next if provided.
- get_next_task()¶
Returns the next active task, which has not been either approved or skipped.
- cancel(user=None)¶
Cancels the workflow state
- finish(user=None)¶
Finishes a successful in progress workflow, marking it as approved and performing the
on_finishaction.
- resume(user=None)¶
Put a STATUS_NEEDS_CHANGES workflow state back into STATUS_IN_PROGRESS, and restart the current task
- copy_approved_task_states_to_revision(revision)¶
Creates copies of previously approved task states with revision set to a different revision.
- all_tasks_with_status()¶
Returns a list of Task objects that are linked with this workflow state's workflow. The status of that task in this workflow state is annotated in the
.statusfield. And a displayable version of that status is annotated in the.status_displayfield.This is different to querying TaskState as it also returns tasks that haven't been started yet (so won't have a TaskState).
- revisions()¶
Returns all revisions associated with task states linked to the current workflow state.
Task¶
任务表示工作流中的各个阶段,必须全部通过,工作流才能成功完成。
数据库字段¶
- class wagtail.models.Task¶
- name¶
(文本)
任务的可读名称。
- active¶
(布尔值)
任务是否启用:启用的任务可以加入工作流并启动。未启用的则不行,并且在 既有工作流中会被跳过。
- content_type¶
(外键,指向
django.contrib.contenttypes.models.ContentType)指向
ContentType对象的外键,该对象表示该任务所属的具体模型。
方法与属性¶
- class wagtail.models.Task
- workflows¶
Returns all
Workflowinstances that use this task.
- active_workflows¶
Return a
QuerySet`of active workflows that this task is part of.
- task_state_class¶
为该任务存储状态信息时要生成的具体任务状态类。若未指定,则为
TaskState。
- classmethod get_verbose_name()¶
Returns the human-readable "verbose name" of this task model e.g "Group approval task".
- specific¶
Returns this object in its most specific subclassed form with all field values fetched from the database. The result is cached in memory.
- start(workflow_state, user=None)¶
Start this task on the provided workflow state by creating an instance of TaskState.
- on_action(task_state, user, action_name, **kwargs)¶
Performs an action on a task state determined by the
action_namestring passed.
- user_can_access_editor(obj, user)¶
Returns
Trueif a user who would not normally be able to access the editor for the object should be able to if the object is currently on this task. Note that returningFalsedoes not remove permissions from users who would otherwise have them.
- user_can_lock(obj, user)¶
Returns
Trueif a user who would not normally be able to lock the object should be able to if the object is currently on this task. Note that returningFalsedoes not remove permissions from users who would otherwise have them.
- user_can_unlock(obj, user)¶
Returns
Trueif a user who would not normally be able to unlock the object should be able to if the object is currently on this task. Note that returningFalsedoes not remove permissions from users who would otherwise have them.
- locked_for_user(obj, user)¶
Returns
Trueif the object should be locked to a given user's edits. This can be used to prevent editing by non-reviewers.
- get_actions(obj, user)¶
Get the list of action strings (name, verbose_name, whether the action requires additional data - see
get_form_for_action) for actions the current user can perform for this task on the given object. These strings should be the same as those able to be passed toon_action.
- get_task_states_user_can_moderate(user, **kwargs)¶
Returns a
QuerySetof the task states the current user can moderate
- deactivate(user=None)¶
Set
activeto False and cancel all in progress task states linked to this task.
- get_form_for_action(action)¶
- get_template_for_action(action)¶
Specifies a template for the workflow action modal.
- classmethod get_description()¶
Returns the task description.
TaskState¶
任务状态存储某个任务在特定修订版本上的进度状态信息。
数据库字段¶
- class wagtail.models.TaskState¶
- workflow_state¶
(外键,指向
WorkflowState)启动此任务状态的工作流状态。
- status¶
(文本)
该修订版本上任务的完成状态。可选值见
TaskState.STATUS_CHOICES)
- content_type¶
(外键,指向
django.contrib.contenttypes.models.ContentType)指向
ContentType对象的外键,该对象表示该任务所属的具体模型。
- started_at¶
(日期/时间)
创建此任务状态的时间。
- finished_at¶
(日期/时间)
此任务状态被取消、拒绝或批准的时间。
- finished_by¶
(外键,指向用户模型)
完成(取消、拒绝、批准)该任务的用户。
- comment¶
(文本)
用户完成任务时通常会添加的文本评论。
方法与属性¶
- class wagtail.models.TaskState
- STATUS_CHOICES¶
status字段可能取值及其可读名称组成的元组。可选值为STATUS_IN_PROGRESS、STATUS_APPROVED、STATUS_CANCELLED、STATUS_REJECTED和STATUS_SKIPPED。
- exclude_fields_in_copy¶
调用
TaskState.copy()方法时不复制的字段列表。
- specific¶
Returns this object in its most specific subclassed form with all field values fetched from the database. The result is cached in memory.
- approve(user=None, update=True, comment='')¶
Approve the task state and update the workflow state.
- reject(user=None, update=True, comment='')¶
Reject the task state and update the workflow state.
- task_type_started_at¶
Finds the first chronological started_at for successive TaskStates - ie started_at if the task had not been restarted.
- cancel(user=None, resume=False, comment='')¶
Cancel the task state and update the workflow state. If
resumeis set to True, then upon update the workflow state is passed the current task asnext_task, causing it to start a new task state on the current task if possible.
- copy(update_attrs=None, exclude_fields=None)¶
Copy this task state, excluding the attributes in the
exclude_fieldslist and updating any attributes to values specified in theupdate_attrsdictionary ofattribute:new valuepairs.
- get_comment()¶
Returns a string that is displayed in workflow history.
This could be a comment by the reviewer, or generated. Use mark_safe to return HTML.
WorkflowTask¶
表示某个任务在特定工作流中的排列顺序。
数据库字段¶
WorkflowPage¶
表示工作流对某个页面及其后代的指派。
数据库字段¶
WorkflowContentType¶
表示工作流对某个 Django 模型的指派。
数据库字段¶
- class wagtail.models.WorkflowContentType¶
-
- content_type¶
(外键,指向
ContentType)指向
ContentType对象的外键,该对象表示被指派到该工作流的模型。
BaseLogEntry¶
一个抽象基类,表示在某个对象上执行某项操作的记录。
数据库字段¶
- class wagtail.models.BaseLogEntry¶
- content_type¶
(外键,指向
django.contrib.contenttypes.models.ContentType)指向
ContentType对象的外键,该对象表示该模型所属的具体模型。
- label¶
(文本)
创建该条目时对象的标题
注意:Wagtail 会尝试使用
get_admin_display_title,或传给LogEntryManager.log_action的对象的字符串表示
- user¶
(外键,指向用户模型)
指向触发该操作的用户的外键。
- data¶
(字典)
每项操作任何额外细节的 JSON 表示。 例如,从页面复制时的源页面 id 与标题,或工作流流转时的工作流 id/名称与下一步 id/名称
- timestamp¶
(日期/时间)
创建该条目的日期/时间。
- content_changed¶
(布尔值)
内容发生变化时可以设为
True的布尔值。
- deleted¶
(布尔值)
对象被删除时可以设为
True的布尔值。用于在站点历史报告中过滤条目。
方法与属性¶
PageLogEntry¶
表示在 Page 上执行某项操作的记录,是 BaseLogEntry 的子类。
数据库字段¶
Comment¶
表示页面上的评论。
数据库字段¶
- class wagtail.models.Comment¶
-
- user¶
(外键,指向用户模型)
指向添加该评论的用户的外键。
- text¶
(文本)
评论的文本内容。
- contentpath¶
(文本)
该评论所附着的字段或 StreamField 区块的路径, 形式为
field或field.streamfield_block_id。
- position¶
(文本)
该评论在其字段中位置的标识符。所用格式 由该字段决定。
- created_at¶
(日期/时间)
创建该评论的日期/时间。
- updated_at¶
(日期/时间)
更新该评论的日期/时间。
- resolved_at¶
(日期/时间)
该评论被解决的日期/时间(若有)。
- resolved_by¶
(外键,指向用户模型)
指向解决该评论的用户的外键(若有)。
CommentReply¶
表示对某个评论串的回复。
数据库字段¶
PageSubscription¶
表示某个用户对页面事件邮件通知的订阅。 目前仅用于评论通知。