python - 获取有关创建新的 Wagtail 页面的父页面

标签 python django wagtail

在创建新页面时,我需要根据父页面的值更改某些字段的默认值。在编辑现有页面时,这不是问题,但在创建新页面时,我需要为字段设置默认值。我已经尝试覆盖管理表单,在初始化 WagtailAdminPageForm 时,parent_page 参数为空。如果我尝试在 Page 子类的 init 方法上执行此操作,则没有包含父信息的 arg 或 kwargs。

有没有办法获取新页面将作为父页面的页面?

这是我在页面构造函数上尝试的

class CMSPage(Page):
    .
    .
    .
    def __init__(self, *args, **kwargs):
        super(BaseContentMixin, self).__init__(*args, **kwargs)

        if hasattr(self.get_parent().specific, 'published_site') and self.get_parent().specific.published_site == 'extranet':
            self.published_site = 'extranet'

这适用于编辑页面,对于新页面,我知道 NoneType 对象没有特定的属性。

Django版本为1.10,Python版本为3.6,Wagtail版本为1.9

最佳答案

在澄清问题后,这里有第二个答案可能更合适。请注意,这需要 Wagtail 1.11.x,目前尚未发布。

解决方案示例代码

首先为您的自定义页面表单创建一个新类,通常在 models.py 或页面模型所在的任何位置。

from wagtail.wagtailadmin.forms import WagtailAdminPageForm

class MyCustomPageForm(WagtailAdminPageForm):

    # Override the __init__ function to update 'initial' form values
    def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs):
        print('parent_page', parent_page, parent_page.id, parent_page.title)
        # update the kwargs BEFORE the init of the super form class
        instance = kwargs.get('instance')
        if not instance.id:
            # only update the initial value when creating a new page
            kwargs.update(initial={
                # 'field': 'value'
                'title': parent_page.id  # can be anything from the parent page
            })
        # Ensure you call the super class __init__
        super(MyCustomPageForm, self).__init__(data, files, *args, **kwargs)
        self.parent_page = parent_page

其次在页面模型定义中,告诉该模型使用您定义的表单类

from wagtail.wagtailcore.models import Page

class MyCustomPage(Page):
    base_form_class = MyCustomPageForm

解决方案说明

  • Wagtail 提供了覆盖在 Wagtail Admin 中构建用于创建和编辑的表单时调用的表单类(注意:不是模型类)的能力。
  • 文档:Customising generated forms
  • 我们的自定义表单类将继承 WagtailAdminPageForm 类。
  • 在这个新的表单类中,我们要定义我们自己的 __init__ 函数,它会在创建表单时调用。
  • 注意 default definition of __init__ on WagtailAdminPageForm 的 Github 代码
  • 为了注入(inject)自定义值,我们将在调用类的 super __init__
  • 之前覆盖 kwargs 中的 initial 数据
  • 我们只想在创建新页面时执行此操作,因此请检查该实例是否没有 id
  • 我们可以访问 parent_page 实例及其中的任何字段
  • 添加自定义初始数据后,我们用更改后的 kwargs 调用 super __init__
  • 注意:要求 Wagtail 1.11.x 的原因是之前的版本在调用类模型时没有添加 parent_page,直到 pull request 3508

关于python - 获取有关创建新的 Wagtail 页面的父页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44330638/

相关文章:

django - 如何根据 ManyToManyField 在 Wagtail 中过滤搜索结果?

Python 前导下划线_variables

python - 在派生自 Django 模型的类上使用 __new__ 不起作用

python - 错误 : Line magic function

django ModelMultipleChoiceField 查询集/过滤器已关联的对象

python - Django 高级搜索

python - Wagtail 渲染页面树

django - 如何获取 wagtail/django 中某个类别内的项目数量?

python - 如何使用python输入更新mysql

python - 给定字典中的键,提取 x 个先前的键值对