Skip to content

Instantly share code, notes, and snippets.

@cnk
Created June 8, 2023 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cnk/4aaeb45ca4d02ee85692626f0a2b0fc3 to your computer and use it in GitHub Desktop.
Save cnk/4aaeb45ca4d02ee85692626f0a2b0fc3 to your computer and use it in GitHub Desktop.
Custom page copy that does NOT copy the original page's revisions
The tricky bit is then getting that view used for the "copy".
We do a lot of patching so it's hard for me to extract a good example of that
from django.urls import path
from .. import views
urlpatterns = [
path('<int:page_id>/event-page-copy/', views.event_page_copy, name='event_page_copy'),
]
@user_passes_test(user_has_any_page_permission)
def event_page_copy(request, page_id):
"""
This short-circuits the normal Page copy flow for EventPages specifically by skipping the intermediate page
that allows you to choose a title, page parent, slug and whether you want to publish the page. This is used
by the per-page [COPY] links on the My Events page.
Instead we:
* Set the parent to the master calendar page
* Autogenerate a valid slug
* Set the page title to the same title as the origin page
Because of these assumptions, we specifically look for EventPages with id `page_id` and 404 if they're not found.
"""
page = get_object_or_404(EventPage, pk=page_id)
parent_page = MasterCalendarPage2.objects.descendant_of(Site.find_for_request(request).root_page).first()
if not page.permissions_for_user(request.user).can_copy_to(parent_page, False):
raise PermissionDenied
next_url = get_valid_next_url_from_request(request)
for fn in hooks.get_hooks('before_copy_page'):
result = fn(request, page)
if hasattr(result, 'status_code'):
return result
# If the slug based on the old page's title isn't available, we generate a new slug that is guaranteed to be unique.
new_slug = slugify(page.title, allow_unicode=True)
if not Page._slug_is_available(new_slug, parent_page):
new_slug = safe_slugify(page, parent_page)
# Copy the page
new_page = page.copy(
recursive=False,
to=parent_page,
update_attrs={
'slug': new_slug,
'original_id': None,
'import_id': None
},
copy_revisions=False,
keep_live=False,
user=request.user,
)
messages.success(request, _("Page '{0}' copied.").format(page.get_admin_display_title()))
for fn in hooks.get_hooks('after_copy_page'):
result = fn(request, page, new_page)
if hasattr(result, 'status_code'):
return result
# Redirect to explore of parent page
if next_url:
return redirect(next_url)
return redirect('wagtailadmin_explore', parent_page.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment