I have a case that uses Page ID as a slug, after creating a new Page, Wagtail provides us a "View live" button but when we click on that button, it provides a wrong URL
The right URL should be ".../property-list/<property-id>"
I have searched on stack overflow, found this thread but the answer is still a mystery: Wrong 'View live' url in Wagtail admin message after page creation when using id as slug
I have followed the Wagtail official document, using Wagtail Hooks to manipulate data. However, no success yet. This is my code:
@hooks.register('after_create_page')
def set_number_and_slug_after_property_page_created(request, page):
page.number = page.slug = str(page.id)
page.save()
new_revision = page.save_revision()
if page.live:
new_revision.publish()
Please help me, thank you.
The after_create_page
hook doesn't work for this, as it's one of the last things to run during the Wagtail admin's page creation view, and the confirmation message (including the old URL) has already been constructed by that point. This can be remedied by using the post_save
signal provided by Django instead - being a more low-level mechanism, it's more closely tied to the act of saving the database record, without Wagtail's admin logic getting in the way.
(It's also a bit more future-proof: Wagtail's after_create_page
hook is designed to only be called when a user goes through the page creation area of the Wagtail admin, so that it can be used to customise that user's path through the admin if appropriate. If there's ever any other route by which a page might be created - like, say, a data import, or using translation tools for a multi-language site - then after_create_page
will be bypassed, but the post_save
signal will still be triggered.)
Assuming your project has a properties
app where you're defining a PropertyPage model, your code can be rewritten to use post_save
as follows - in properties/signals.py
:
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import PropertyPage
@receiver(post_save)
def set_number_and_slug_after_property_page_created(sender, instance, created, **kwargs):
if issubclass(sender, PropertyPage) and created:
page = instance
page.number = page.slug = str(page.id)
page.save()
new_revision = page.save_revision()
if page.live:
new_revision.publish()
Then, to connect this signal up on server startup, create a properties/apps.py
containing the following (or just add / edit the ready
method if you have an AppConfig class there already):
from django.apps import AppConfig
class PropertiesConfig(AppConfig):
name = 'properties'
def ready(self):
from . import signals