Recipe: automatic redirect creation on url edit (#5002)

This commit is contained in:
Matthew Linares 2019-01-22 11:22:47 +00:00 committed by Matt Westcott
parent 6890f8ef76
commit a0b4efd414
2 changed files with 27 additions and 0 deletions

View file

@ -340,6 +340,7 @@ Contributors
* mukesh5
* frmdstryr
* Aidarbek Suleimenov
* Matthew Linares
Translators
===========

View file

@ -196,3 +196,29 @@ Here, ``blogs.filter(tags__name=tag)`` invokes a reverse Django QuerySet filter
Iterating through ``page.tags.all`` will display each tag associated with ``page``, while the link(s) back to the index make use of the filter option added to the ``BlogIndexPage`` model. A Django query could also use the ``tagged_items`` related name field to get ``BlogPage`` objects associated with a tag.
This is just one possible way of creating a taxonomy for Wagtail objects. With all of the components for a taxonomy available through Wagtail, you should be able to fulfil even the most exotic taxonomic schemes.
Have redirects created automatically when changing page slug
------------------------------------------------------------
You may want redirects created automatically when a url gets changed in the admin so as to avoid broken links. You can add something like the following block to a ``wagtail_hooks.py`` file within one of your project's apps.
.. code-block:: python
from wagtail.core import hooks
from wagtail.contrib.redirects.models import Redirect
# Create redirect when editing slugs
@hooks.register('before_edit_page')
def create_redirect_on_slug_change(request, page):
if request.method == 'POST':
if page.slug != request.POST['slug']:
Redirect.objects.create(
old_path=page.url[:-1],
site=page.get_site(),
redirect_page=page
)
Note: This does not work in some cases e.g. when you redirect a page, create a new page in that url and then move the new one. It should be helpful in most cases however.