在Django + Wagtail项目中,我有一个自定义方法,我从模型save()
方法调用。它工作 - 但每次我通过wagtail管理界面保存一个实例,这个方法被调用两次 - 为什么?
# models.py
from wagtail.core.models import Page
class ArticlePage(Page):
def my_method(self):
print('I will be printed twice on save...')
def save(self, *args, **kwargs):
self.my_method()
super().save(*args, **kwargs)
按照Håken Lid的建议使用traceback.print_stack
我发现该方法首先通过
File ".../.venv/lib/python3.6/site-packages/wagtail/admin/views/pages.py", line 336, in edit
submitted_for_moderation=is_submitting,
File ".../.venv/lib/python3.6/site-packages/wagtail/core/models.py", line 653, in save_revision
self.save(update_fields=update_fields)
和第二次通过
File ".../.venv/lib/python3.6/site-packages/wagtail/admin/views/pages.py", line 343, in edit
revision.publish()
File ".../.venv/lib/python3.6/site-packages/wagtail/core/models.py", line 1498, in publish
page.save()
但即使有了这些信息,我也不知道如何只在第二次保存时触发我的方法...
ENV:
Django 2.0.4
Wagtail 2.0.1
答案 0 :(得分:1)
如果您想在页面发布上执行某些操作,可以使用以下page_published
信号:
from django.dispatch import receiver
from wagtail.core.signals import page_published
@receiver(page_published)
def do_stuff_on_page_published(instance, **kwargs):
print('=======================',instance,kwargs)
如果是保存,您还可以检查update_fields
中的kwargs
参数:
def save(self, *args, **kwargs):
if kwargs.get('update_fields'):
pass # save not called from publish
# do_stuff_on_save()
else:
pass
# do_stuff_on_publish()
return super().save(*args, **kwargs)
有关wagtail信号代码的详细信息,请访问此link 这是官方文档 http://docs.wagtail.io/en/v1.7/reference/signals.html