skillbox/server/core/migrate_i18n_pages.py

54 lines
1.7 KiB
Python

from wagtail.models import Locale, Page
from books.models.module import Module
from books.models.topic import Topic
from core.logger import get_logger
logger = get_logger(__name__)
# todo: make this a django command
# todo: add language to translate to as an argument
# todo: write a test maybe
def migrate_i18n(slug: str, original_slug: str):
"""
Migrate a module and its children to a new locale and links it to
its translation in the original locale.
@param slug: the slug of the module to migrate
@param original_slug: the slug of the module in the original locale
"""
module = Module.objects.get(slug=slug)
original = Module.objects.get(slug=original_slug)
en = Locale.objects.get(language_code="en")
logger.debug("starting this")
topic: Topic = module.get_parent()
try:
logger.debug("getting translation")
en_topic = topic.get_translation(en)
except Page.DoesNotExist:
logger.debug("creating translation")
en_topic = topic.copy_for_translation(en)
revision = en_topic.latest_revision
en_topic.publish(revision)
logger.debug(f"new topic {en_topic.pk}")
module.locale = en
if original is not None:
translation_key = original.translation_key
module.translation_key = translation_key
module.save()
chapters = module.get_children()
for chapter in chapters:
chapter.locale = en
chapter.save()
content_blocks = chapter.get_children()
for content_block in content_blocks:
content_block.locale = en
content_block.save()
module.move(en_topic, "last-child")
print(f"go {module.title} {module.locale.language_code}")