问题
In a Django+Wagtail project, I have a custom method which I call from the model save() method. It works - but everytime I save an instance via the wagtail admin interface, this method is called twice - why?
# 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)
By using traceback.print_stack as suggested by Håken Lid I've found out that the method is first called via 
  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)
and the second time via
  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()
But even with this information I'm not aware how to only trigger my method on the second save...
Env:
Django 2.0.4
Wagtail 2.0.1  
回答1:
In case you want to do something on page publish, You can use the page_published signals as below:
    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)
In case of save, you can also check the update_fields argument in the 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)
For more info about wagtail signal code visit this link and this for the official docs http://docs.wagtail.io/en/v1.7/reference/signals.html
来源:https://stackoverflow.com/questions/50327528/custom-wagtail-page-model-save-method-called-twice