我想自动生成字段内容的基础上,另一个编辑器填充的领域为wagtail页面模型的页面保存。
我遵循了wagtail文档,我能够在页面保存/发布上以编程方式填充和保存字段:
from wagtail.models import Page
from wagtail.admin.forms import WagtailAdminPageForm
class TestPageForm(WagtailAdminPageForm):
def clean(self):
cleaned_data = super().clean()
print("-> called TestPageForm.clean()")
return cleaned_data
def save(self, commit=True):
print(f"1 {commit=}")
page = super().save(commit=False)
print(f"2 {commit=}")
print("-> called TestPageForm.save()")
# process something, save result to instance field, e.g.:
# page.pdf_cover_image = get_cover_image(self.cleaned_data["pdf"])
if commit:
print(f"{commit=}: calling page.save()")
page.save()
return page
class TestPage(Page):
base_form_class = TestPageForm
但是,形式clean()
和save()
方法被多次调用,即使我根本不希望它们被调用:
编辑页面
通过wagtail后端请求页面示例(“编辑页面”):http://127.0.0.1:8000/admin/pages/139/edit/
⇒
[10/May/2023 10:35:37] "GET /admin/pages/139/edit/ HTTP/1.1" 200 71082
[...assets...]
-> called TestPageForm.clean()
1 commit=False
2 commit=False
-> called TestPageForm.save()
[10/May/2023 10:35:37] "GET /admin/pages/139/edit/preview/?in_preview_panel=true&mode= HTTP/1.1" 200 0
[10/May/2023 10:35:37] "DELETE /admin/pages/139/edit/preview/ HTTP/1.1" 200 17
-> called TestPageForm.clean()
[10/May/2023 10:35:37] "POST /admin/pages/139/edit/preview/ HTTP/1.1" 200 40
-> called TestPageForm.clean()
1 commit=False
-> called TestPageForm.clean()
2 commit=False
-> called TestPageForm.save()
1 commit=False
2 commit=False
-> called TestPageForm.save()
[10/May/2023 10:35:37] "GET /admin/pages/139/edit/preview/?in_preview_panel=true&mode= HTTP/1.1" 200 0
保存页面
[10/May/2023 10:35:37] "GET /admin/pages/139/edit/preview/?in_preview_panel=true&mode= HTTP/1.1" 200 0
-> called TestPageForm.clean()
1 commit=False
2 commit=False
-> called TestPageForm.save()
[10/May/2023 10:38:10] "POST /admin/pages/139/edit/ HTTP/1.1" 302 0
[10/May/2023 10:38:10] "GET /admin/pages/8/ HTTP/1.1" 200 45356
所以在页面保存中,clean()
和save()
方法只被调用一次,但是由于commit
总是False
,我无法区分所有这些clean-and-save-calls。
那么我如何触发一个自定义的保存()-action,它只会被调用一次,而且只会在page save()上调用?
1条答案
按热度按时间yfwxisqw1#
如果你在Wagtail 4+上,那么清理/保存将被预览面板调用,不管它是否可见(这不应该发生在IMO上,但现在就是这样)。
我有一些沉重的领域计算代码,我需要转移出清洁时,我升级,由于这一点。我使用了after create/edit hooks:
这只会在编辑器点击保存/保存草稿时触发,他们需要这样做才能在实时预览中看到影响此计算的更改的任何渲染效果。