diff --git a/docs/quick-start.md b/docs/quick-start.md index 41cf490..900707b 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -53,3 +53,5 @@ python manage.py update_vector_indexes ``` To skip the prompt, use the `--noinput` flag. + +Indexes can also be set to update automatically when a page is published, by setting `WAGTAIL_VECTOR_INDEX_UPDATE_ON_PUBLISH` to true inside your settings file. diff --git a/src/wagtail_vector_index/apps.py b/src/wagtail_vector_index/apps.py index f18c949..de06fd2 100644 --- a/src/wagtail_vector_index/apps.py +++ b/src/wagtail_vector_index/apps.py @@ -1,7 +1,18 @@ from django.apps import AppConfig +from django.conf import settings class WagtailVectorIndexAppConfig(AppConfig): label = "wagtail_vector_index" name = "wagtail_vector_index" verbose_name = "Wagtail Vector Index" + + def ready(self): + update_on_publish = getattr( + settings, "WAGTAIL_VECTOR_INDEX_UPDATE_ON_PUBLISH", False + ) + if update_on_publish: + # Register signals to update indexes on publish + from wagtail_vector_index import signals + + signals.register_signal_handlers() diff --git a/src/wagtail_vector_index/signals.py b/src/wagtail_vector_index/signals.py new file mode 100644 index 0000000..a2ac232 --- /dev/null +++ b/src/wagtail_vector_index/signals.py @@ -0,0 +1,23 @@ +from django.apps import apps +from wagtail.signals import page_published + + +def run_command_on_publish(sender, **kwargs): + # Check page is live as not to leak draft content + if kwargs["instance"].live: + if hasattr(kwargs["instance"], "get_vector_index"): + index = kwargs["instance"].get_vector_index() + index.rebuild_index() + + +def register_signal_handlers(): + from wagtail_vector_index.models import VectorIndexedMixin + + indexes = [ + model + for model in apps.get_models() + if issubclass(model, VectorIndexedMixin) and not model._meta.abstract + ] + + for index in indexes: + page_published.connect(run_command_on_publish, sender=index) diff --git a/tests/testapp/settings.py b/tests/testapp/settings.py index 3befc6f..b2b1da3 100644 --- a/tests/testapp/settings.py +++ b/tests/testapp/settings.py @@ -263,3 +263,5 @@ }, }, } + +WAGTAIL_VECTOR_INDEX_UPDATE_ON_PUBLISH = True # Defaults to false