### Set up Wagtail Project on Windows Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/1-project-set-up.md PowerShell commands to create a virtual environment, activate it, install Wagtail and Wagtail Localize, start a new Wagtail project, and navigate into the project directory. ```powershell # Create a new virtual environment in a 'tutorial-venv' folder # This isolates installed dependencies from other projects python -m venv tutorial-venv # Activate the virtual environment # Note: If you come back to this tutorial later, you will need to # run this again to reactivate the environment .\tutorial-venv\Script\Activate.ps1 # Install Wagtail and Wagtail Localize pip install wagtail wagtail-localize # Start a new project wagtail start tutorial cd .\tutorial ``` -------------------------------- ### Set up Wagtail Project on Mac OS and GNU/Linux Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/1-project-set-up.md Commands to create a virtual environment, activate it, install Wagtail and Wagtail Localize, start a new Wagtail project, and navigate into the project directory. ```shell # Create a new virtual environment in a 'tutorial-venv' folder # This isolates installed dependencies from other projects python3 -m venv tutorial-venv # Activate the virtual environment # Note: If you come back to this tutorial later, you will need to # run this again to reactivate the environment source ./tutorial-venv/bin/activate # Install Wagtail and Wagtail Localize pip install wagtail wagtail-localize # Start a new project wagtail start tutorial cd ./tutorial ``` -------------------------------- ### Start Wagtail Development Server Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/1-project-set-up.md Command to start the local development server for the Wagtail project. ```shell python manage.py runserver ``` -------------------------------- ### Install wagtail-localize using pip Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Installs the wagtail-localize Python package using the pip package manager. ```shell pip install wagtail-localize ``` -------------------------------- ### Install Wagtail Localize Testing Dependencies Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Installs the package with testing dependencies using pip, allowing for local development and testing of the wagtail-localize project. ```Shell pip install "pip>=21.3" pip install -e '.[testing]' -U ``` -------------------------------- ### Install Wagtail Localize using Flit Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Installs the wagtail-localize project locally using flit, a tool for packaging Python projects. This is an alternative to pip installation for development. ```Shell pip install "flit>=3.8.0" flit install ``` -------------------------------- ### Create Wagtail Superuser Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/1-project-set-up.md Command to create an administrator user for the Wagtail site. ```shell python manage.py createsuperuser --email admin@example.com --username admin ``` -------------------------------- ### Add wagtail_localize to INSTALLED_APPS Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Configures the Django project to include wagtail_localize in the INSTALLED_APPS setting. ```python INSTALLED_APPS = [ # ... "wagtail_localize", # ... ] ``` -------------------------------- ### Migrate Wagtail Database Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/1-project-set-up.md Command to migrate the database for the first time, creating the 'db.sqlite3' file. ```shell python manage.py migrate ``` -------------------------------- ### Install Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Installs the wagtail-localize package using pip. This is the primary step for integrating the plugin into a Wagtail project. ```Shell pip install wagtail-localize ``` -------------------------------- ### Initialize pre-commit Hooks Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Installs the pre-commit Git hooks for the wagtail-localize project. This ensures code quality checks are run automatically before commits. ```Shell # go to the project directory $ cd wagtail-localize # initialize pre-commit $ pre-commit install ``` -------------------------------- ### Install wagtail-localize-git Plugin Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md Installs the `wagtail-localize-git` plugin using pip and adds it to the Django project's `INSTALLED_APPS` setting. This plugin is necessary for integrating Wagtail Localize with Git repositories. ```shell pip install wagtail-localize-git ``` ```python INSTALLED_APPS = [ # ... "wagtail_localize", # Insert this "wagtail_localize_git", # ... ] ``` -------------------------------- ### Install Wagtail Localize with Google Cloud Plugin Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Installs the wagtail-localize package with the necessary dependencies for Google Cloud Translation integration. This command-line instruction ensures all required libraries are available. ```Bash pip install wagtail-localize[google] ``` -------------------------------- ### Integrate Entrypoint Script into Dockerfile Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md This Dockerfile instruction specifies the bash script as the entrypoint for the container, ensuring it runs when the container starts. The path to the script should be updated if it differs. ```dockerfile ENTRYPOINT ["/app/docker-entrypoint.sh"] ``` -------------------------------- ### Run Interactive Tox Test Environment Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Starts a tox environment for interactive testing, allowing direct access to the test application via a web interface. ```Shell tox -e interactive ``` -------------------------------- ### Prevent live translations from being published immediately Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Disables the automatic publishing of live versions of models that support drafts when they are submitted for translation. ```python WAGTAILLOCALIZE_SYNC_LIVE_STATUS_ON_TRANSLATE = False ``` -------------------------------- ### Disable default translation mode globally Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Sets the global default translation mode to 'simple' by disabling automatic translation mode for new translations. ```python WAGTAIL_LOCALIZE_DEFAULT_TRANSLATION_MODE = "simple" ``` -------------------------------- ### Implement Custom Job Backend for Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/configure-background-tasks.md This example demonstrates how to create a custom job backend for Wagtail Localize by subclassing `BaseJobBackend`. It includes placeholders for initialization and task enqueuing logic, allowing integration with different queueing systems. ```python from wagtail_localize.tasks import BaseJobBacked class MyJobBackend(BaseJobBackend): def __init__(self, options): # Any set up code goes here. Note that the 'options' parameter contains the value of WAGTAILLOCALIZE_JOBS["OPTIONS"] pass def enqueue(self, func, args, kwargs): # func is a function object to call # args is a list of positional arguments to pass into the function when it's called # kwargs is is a dict of keyword arguments to pass into the function when it's called pass ``` -------------------------------- ### Set default translation mode per model Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Configures a specific Django model to use the 'simple' translation mode by setting the localize_default_translation_mode attribute. ```python from wagtail.models import Page class MyPage(Page): localize_default_translation_mode = "simple" # ... ``` -------------------------------- ### Heroku SSH Setup Script Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md A bash script for regular (non-container) Heroku apps that decodes the `SSH_PRIVATE_KEY` environment variable, saves it as `id_rsa` in the `.ssh` directory, and configures SSH to accept it. This allows Heroku apps to use the private key for Git operations. ```bash #!/usr/bin/env bash # Copy SSH private key to file, if set # This is used for talking to GitHub over an SSH connection if [ $SSH_PRIVATE_KEY ]; then echo "Generating SSH config" SSH_DIR=/app/.ssh mkdir -p $SSH_DIR chmod 700 $SSH_DIR echo $SSH_PRIVATE_KEY | base64 --decode > $SSH_DIR/id_rsa chmod 400 $SSH_DIR/id_rsa cat << EOF > $SSH_DIR/config StrictHostKeyChecking no EOF chmod 600 $SSH_DIR/config echo "Done!" fi ``` -------------------------------- ### Keep translation data on deletion Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/installation.md Disables the automatic removal of translation data when the source or destination of a translation is deleted, preserving related data. ```python WAGTAILLOCALIZE_DISABLE_ON_DELETE = True ``` -------------------------------- ### Install wagtail-localize.modeladmin Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/modeladmin.md Add 'wagtail_localize.modeladmin' to your Django project's INSTALLED_APPS to enable ModelAdmin translation support. ```python INSTALLED_APPS = [ # ... "wagtail_localize.modeladmin", ] ``` -------------------------------- ### Display Translation Details in Wagtail Report Source: https://github.com/wagtail/wagtail-localize/blob/main/wagtail_localize/templates/wagtail_localize/admin/translations_report_results.html This snippet shows how to extend Wagtail's base report results template to display translation information. It iterates through a list of translations, showing the content type, source, target, and status. It includes logic to get and display the target instance and its edit URL. ```html {% extends 'wagtailadmin/reports/base_report_results.html' %} {% load i18n wagtailadmin_tags %} {% block results %} {% for translation in object_list %} {% endfor %} {% trans 'Content type' %} {% trans 'Source' %} {% trans 'Target' %} {% trans 'Status' %} {{ translation.source.specific_content_type.name|capfirst }} [{{ translation.source.object_repr }} ({{ translation.source.locale }})]({{ translation.source.get_source_instance_edit_url }}) {% with translation.get_target_instance as target_instance %} [{{ target_instance.get_admin_display_title|default:target_instance }} ({{ translation.target_locale }})]({{ translation.get_target_instance_edit_url }}) {% endwith %} {{ translation.get_status_display }} {% endblock %} {% block no_results_message %} {% trans "No translations found." %} {% endblock %} ``` -------------------------------- ### Wagtail-Localize Release Commands Source: https://github.com/wagtail/wagtail-localize/wiki/Home This snippet provides the command-line interface commands necessary for the Wagtail-Localize release process. It includes steps for activating the virtual environment, managing translations, building frontend assets, and publishing to PyPI. ```bash source .venv/bin/activate make messages sh scripts/fetch-translations.sh make compile-messages npm run build flit build flit publish ``` -------------------------------- ### Configure INSTALLED_APPS Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/3-content.md This Python code snippet shows how to add the newly created 'blog' app and the necessary Wagtail Localize apps to your Django project's `INSTALLED_APPS` setting. This enables the blog functionality and localization features. ```python INSTALLED_APPS = [ "home", "search", # Insert this "blog", "wagtail_localize", "wagtail_localize.locales", "wagtail.contrib.forms", "wagtail.contrib.redirects", # ... ] ``` -------------------------------- ### Run All pre-commit Checks Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Executes all configured pre-commit hooks on all files in the repository. This is useful for a comprehensive code quality check. ```Shell $ pre-commit run --all-files ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Executes the test suite using tox, a versatile tool for automating testing in Python. This command runs all defined test environments. ```Shell tox ``` -------------------------------- ### Prevent Overriding Synchronized Field in Wagtail Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/field-configuration.md This Python code example shows how to prevent a 'slug' field, configured as synchronized, from being overridden in translated versions of a Wagtail page. It achieves this by passing `overridable=False` to the `SynchronizedField` constructor within `override_translatable_fields`. ```python from wagtail.models import Page from wagtail_localize.fields import SynchronizedField class BlogPage(Page): body = RichTextField() # Make the slug synchronised, but don't allow it to be overridden on translations override_translatable_fields = [ SynchronizedField("slug", overridable=False), ] ``` -------------------------------- ### Migrate Database for Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/2-configure-wagtail-localize.md This shell command runs the Django database migration process to set up the necessary tables for Wagtail Localize. ```Shell python manage.py migrate ``` -------------------------------- ### Configure SSH Key in Docker Entrypoint Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md This bash script sets up an SSH directory and configures the SSH private key for secure connections, typically used for services like GitHub. It decodes a base64 encoded private key and sets appropriate permissions. ```bash #!/usr/bin/env bash # Copy SSH private key to file, if set # This is used for talking to GitHub over an SSH connection if [ $SSH_PRIVATE_KEY ]; then echo "Generating SSH config" SSH_DIR=/app/.ssh mkdir -p $SSH_DIR chmod 700 $SSH_DIR echo $SSH_PRIVATE_KEY | base64 --decode > $SSH_DIR/id_rsa chmod 400 $SSH_DIR/id_rsa cat << EOF > $SSH_DIR/config StrictHostKeyChecking no EOF chmod 600 $SSH_DIR/config echo "Done!" fi exec "$@" ``` -------------------------------- ### Create Django Blog App Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/3-content.md This command initiates a new Django application named 'blog' within your Wagtail project. This app will house the models and logic for your blog functionality. ```shell python manage.py startapp blog ``` -------------------------------- ### Configure Wagtail Localize Git Settings Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md Sets the necessary Django settings for the `wagtail-localize-git` plugin. `WAGTAILLOCALIZE_GIT_URL` specifies the SSH clone URL of the repository, and `WAGTAILLOCALIZE_GIT_CLONE_DIR` defines the local directory for cloning. ```python WAGTAILLOCALIZE_GIT_URL = "git@github.com:mozilla-l10n/mozilla-donate-content.git" WAGTAILLOCALIZE_GIT_CLONE_DIR = "/tmp/wagtail-content-for-pontoon.git" ``` -------------------------------- ### Configure INSTALLED_APPS for Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Adds 'wagtail_localize' and 'wagtail_localize.locales' to the Django project's INSTALLED_APPS. This enables the plugin's features and replaces Wagtail's default locale app. ```Python INSTALLED_APPS = [ # ... "wagtail_localize", "wagtail_localize.locales", # This replaces "wagtail.locales" # ... ] ``` -------------------------------- ### Wagtail-localize Models Overview Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/ref/models/translation-management.md Provides an overview of the main translation management models in wagtail-localize: TranslatableObject, TranslationSource, Translation, and TranslationLog. These models are central to how wagtail-localize handles the translation workflow for Wagtail content. ```Python from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ from wagtail.core.models import Locale class TranslatableObject(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name="translatable_objects", verbose_name=_("content type") ) object_id = models.CharField(max_length=255, verbose_name=_("object id")) content_object = GenericForeignKey( "content_type", "object_id" ) locale = models.ForeignKey( Locale, on_delete=models.CASCADE, related_name="translatable_objects", verbose_name=_("locale") ) class Meta: unique_together = ["content_type", "object_id", "locale"] class TranslationSource(models.Model): translatable_object = models.ForeignKey( TranslatableObject, on_delete=models.CASCADE, related_name="sources", verbose_name=_("translatable object") ) field_name = models.CharField(max_length=255, verbose_name=_("field name")) field_value = models.TextField(verbose_name=_("field value")) translated_value = models.TextField(blank=True, verbose_name=_("translated value")) translated_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="translation_sources", verbose_name=_("translated by") ) translated_at = models.DateTimeField(null=True, blank=True, verbose_name=_("translated at")) class Translation(models.Model): source = models.ForeignKey( TranslationSource, on_delete=models.CASCADE, related_name="translations", verbose_name=_("source") ) locale = models.ForeignKey( Locale, on_delete=models.CASCADE, related_name="translations", verbose_name=_("locale") ) text = models.TextField(verbose_name=_("text")) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("created at")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("updated at")) class TranslationLog(models.Model): source = models.ForeignKey( TranslationSource, on_delete=models.CASCADE, related_name="logs", verbose_name=_("source") ) locale = models.ForeignKey( Locale, on_delete=models.CASCADE, related_name="translation_logs", verbose_name=_("locale") ) message = models.TextField(verbose_name=_("message")) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("created at")) ``` -------------------------------- ### Dummy Translator for Testing Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Provides a dummy translator for testing Wagtail Localize without external services. This translator simply reverses strings. ```python WAGTAILLOCALIZE_MACHINE_TRANSLATOR = { "CLASS": "wagtail_localize.machine_translators.dummy.DummyTranslator", } ``` -------------------------------- ### Collect Static Assets for Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Runs the Django collectstatic management command to gather all necessary static assets for the Wagtail Localize editing interface. ```Shell python manage.py collectstatic ``` -------------------------------- ### Query Pages with Snippet Tags in Wagtail Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/tips.md This Python code snippet demonstrates how to query Wagtail `BlogPage` objects that are linked to a `Tag` snippet. It handles cases where synchronous translation is enabled or disabled by querying for tags in both the default and current locale, ensuring accurate filtering. The snippet includes model definitions for `Tag` and `BlogPage`, and a `get_context` method to perform the filtered query. ```python from django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as _ from wagtail.snippets.models import register_snippet from wagtail.models import TranslatableMixin, Page @register_snippet class Tag(TranslatableMixin, models.Model): tag = models.CharField(_("Tag"), max_length=255) def __str__(self): return self.tag class BlogPage(Page): my_tag = models.ForeignKey( "snippets.Tag", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) if self.my_tag: default_tag = self.my_tag.get_translation(self.my_tag.get_default_locale()) context['pages'] = BlogPage.objects.live().filter(Q(locale=self.locale), Q(my_tag=default_tag) | Q(my_tag=self.my_tag)).distinct() return context ``` -------------------------------- ### Update Database Migrations Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/3-content.md These Django management commands are essential for applying the model changes defined in your `blog` app to the database. `makemigrations` creates the migration files, and `migrate` applies them. ```shell python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Enable LocaleMiddleware Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/2-configure-wagtail-localize.md This Python code snippet shows how to enable Django's LocaleMiddleware by inserting 'django.middleware.locale.LocaleMiddleware' into the MIDDLEWARE setting to handle browser language detection and redirection. ```Python MIDDLEWARE = [\n "django.contrib.sessions.middleware.SessionMiddleware",\n "django.middleware.common.CommonMiddleware",\n "django.middleware.csrf.CsrfViewMiddleware",\n "django.contrib.auth.middleware.AuthenticationMiddleware",\n "django.contrib.messages.middleware.MessageMiddleware",\n "django.middleware.clickjacking.XFrameOptionsMiddleware",\n "django.middleware.security.SecurityMiddleware",\n # Insert this here\n "django.middleware.locale.LocaleMiddleware",\n "wagtail.contrib.redirects.middleware.RedirectMiddleware",\n] ``` -------------------------------- ### Add Wagtail Localize to INSTALLED_APPS Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/2-configure-wagtail-localize.md This Python code snippet shows how to add 'wagtail_localize' and 'wagtail_localize.locales' to your Django project's INSTALLED_APPS setting to enable Wagtail Localize functionality. ```Python INSTALLED_APPS = [\n "home",\n "search",\n # Insert these here\n "wagtail_localize",\n "wagtail_localize.locales",\n "wagtail.contrib.forms",\n "wagtail.contrib.redirects",\n # ...\n] ``` -------------------------------- ### Define Wagtail Blog Models Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/3-content.md This Python code defines the data models for the blog functionality using Django and Wagtail. It includes models for ImageBlock, StoryBlock (StreamField), BlogCategory (translatable snippet), BlogPostPage, and BlogIndexPage, along with their respective fields and panel configurations. ```python from django.db import models from wagtail import blocks from wagtail.admin.panels import FieldPanel from wagtail.fields import StreamField from wagtail.models import Page, TranslatableMixin from wagtail.images.blocks import ImageChooserBlock from wagtail.snippets.models import register_snippet class ImageBlock(blocks.StructBlock): image = ImageChooserBlock() caption = blocks.CharBlock(required=False) class Meta: icon = "image" class StoryBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.RichTextBlock() image = ImageBlock() @register_snippet class BlogCategory(TranslatableMixin): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPostPage(Page): publication_date = models.DateField(null=True, blank=True) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.SET_NULL, null=True ) body = StreamField(StoryBlock()) category = models.ForeignKey( BlogCategory, on_delete=models.SET_NULL, null=True, related_name="blog_posts" ) content_panels = Page.content_panels + [ FieldPanel("publication_date"), FieldPanel("image"), FieldPanel("body"), FieldPanel("category"), ] parent_page_types = ["blog.BlogIndexPage"] class BlogIndexPage(Page): introduction = models.TextField(blank=True) content_panels = Page.content_panels + [ FieldPanel("introduction"), ] parent_page_types = ["home.HomePage"] ``` -------------------------------- ### Extend Wagtail Slim Header with Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/wagtail_localize/templates/wagtail_localize/admin/includes/generic_header.html This snippet demonstrates how to extend Wagtail's slim header template using Django's template inheritance. It includes loading Wagtail admin tags and internationalization tags, and defines blocks for header content and actions, incorporating side panel toggles. ```Django Template {% extends 'wagtailadmin/shared/headers/slim_header.html' %} {% load wagtailadmin_tags i18n %} {% block header_content %} {% blocktrans trimmed with title=instance object_type=model_opts.verbose_name %}Editing {{ object_type }} {{ title }}{% endblocktrans %} {% endblock %} {% block actions %} {% with nav_icon_classes='w-w-4 w-h-4' nav_icon_button_classes='w-h-slim-header w-bg-transparent w-box-border w-py-3 w-px-3 w-flex w-justify-center w-items-center w-outline-offset-inside w-text-grey-400 w-transition hover:w-transform hover:w-scale-110 hover:w-text-primary focus:w-text-primary' %} {% include "wagtailadmin/shared/side_panel_toggles.html" %} {% endwith %} {% endblock %} ``` -------------------------------- ### Configure Google Cloud Translation with CREDENTIALS_PATH Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Sets up Wagtail Localize to use Google Cloud Translation by specifying the path to the service account key file. This method is recommended when key files can be securely managed. ```Python WAGTAILLOCALIZE_MACHINE_TRANSLATOR = { "CLASS": "wagtail_localize.machine_translators.google.GoogleCloudTranslator", "OPTIONS": { "CREDENTIALS_PATH": "/path/to/keyfile.json", "PROJECT_ID": "", }, } ``` -------------------------------- ### Wagtail Localize Models: String, TranslationContext, Template, StringTranslation Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/ref/models/translation-memory.md These Python models represent the fundamental components of Wagtail Localize's translation memory. They manage source strings, their translations, associated locales, and contextual data for translatable objects. ```python from django.db import models from wagtail_localize.locale import Locale from wagtail_localize.model_utils import TranslatableObject class String(models.Model): """A source string to be translated.""" key = models.TextField(unique=True) def __str__(self): return self.key class TranslationContext(models.Model): """Context for a translation.""" string = models.ForeignKey(String, on_delete=models.CASCADE, related_name="contexts") context = models.TextField(blank=True) def __str__(self): return f"{self.string.key} ({self.context[:50]}...)" class Template(models.Model): """A template for a translatable object.""" name = models.TextField(unique=True) def __str__(self): return self.name class StringTranslation(models.Model): """A translation of a string.""" string = models.ForeignKey(String, on_delete=models.CASCADE, related_name="translations") locale = models.ForeignKey(Locale, on_delete=models.CASCADE, related_name="translations") context = models.ForeignKey(TranslationContext, on_delete=models.SET_NULL, null=True, blank=True, related_name="translations") translation = models.TextField() translatable_object = models.ForeignKey(TranslatableObject, on_delete=models.CASCADE, related_name="translations") def __str__(self): return f"{self.string.key} ({self.locale.language_code})" ``` -------------------------------- ### Wagtail Localize Locale Listing Template Source: https://github.com/wagtail/wagtail-localize/blob/main/wagtail_localize/locales/templates/wagtaillocales/index.html This snippet shows a Django template for listing and managing locales in Wagtail. It utilizes Wagtail's template tags and includes logic for sorting and displaying locale information, along with links to edit individual locales. ```Django Template {% extends "wagtailadmin/generic/index.html" %} {% load wagtailadmin_tags i18n %} {% block listing %} {% for locale in locales %} {% endfor %} {% if ordering == "name" %} [{% trans "Language" %}]({% url 'wagtaillocales:index' %}) {% else %} [{% trans "Language" %}]({% url 'wagtaillocales:index' %}?ordering=name) {% endif %} {% trans "Usage" %} [{{ locale }}]({% url 'wagtaillocales:edit' locale.id %}) {% if not locale.language_code_is_valid %} {% trans "This locale's language code is not supported" as error %} {% include "wagtaillocales/_icon.html" with error=error only %} {% endif %} {# TODO Make this translatable #} {{ locale.num_pages }} pages{% if locale.num_others %} + {{ locale.num_others }} others{% endif %} {% endblock %} ``` -------------------------------- ### Configure DeepL Translator Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Sets up the DeepL machine translator for Wagtail Localize. Requires an API key and optionally allows setting formality preferences and glossary IDs for specific language pairs. A timeout can also be configured. ```python WAGTAILLOCALIZE_MACHINE_TRANSLATOR = { "CLASS": "wagtail_localize.machine_translators.deepl.DeepLTranslator", "OPTIONS": { "AUTH_KEY": "", "FORMALITY": "", "GLOSSARY_IDS": { ("EN", "ES"): "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ("EN", "FR"): "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", }, "TIMEOUT": 30, }, } ``` -------------------------------- ### Configure LibreTranslate Translator Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Configures the LibreTranslate machine translator for Wagtail Localize. Users need an API key or can host their own instance. The configuration includes the LibreTranslate URL, API key, and an optional timeout setting. ```python WAGTAILLOCALIZE_MACHINE_TRANSLATOR = { "CLASS": "wagtail_localize.machine_translators.libretranslate.LibreTranslator", "OPTIONS": { "LIBRETRANSLATE_URL": "https://libretranslate.org", "API_KEY": "", "TIMEOUT": 40 }, } ``` -------------------------------- ### Run Specific Tox Test Environment Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Runs tests within a specific tox environment, defined by Python version, Django version, and Wagtail version. This allows for targeted testing. ```Shell tox -e python3.13-django5.2-wagtail7.0 ``` -------------------------------- ### Configure Chooser URLs in JavaScript Source: https://github.com/wagtail/wagtail-localize/blob/main/wagtail_localize/templates/wagtail_localize/admin/edit_translation.html Initializes JavaScript variables for Wagtail's chooser URLs, including image, document, and page choosers. This is crucial for integrating media and content selection into the translation interface. ```javascript if (typeof window.chooserUrls === "undefined") { window.chooserUrls = { imageChooser: "{% url \"wagtailimages\_chooser:choose\" %}", documentChooser: "{% url \"wagtaildocs\_chooser:choose\" %}", pageChooser: "{% url \"wagtailadmin_choose_page\" %}", } } ``` -------------------------------- ### Configure Django RQ for Wagtail Localize Jobs Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/configure-background-tasks.md This snippet shows how to configure Wagtail Localize to use Django RQ for background jobs. It specifies the backend class and the Django RQ queue to use for pushing tasks. ```python WAGTAILLOCALIZE_JOBS = { "BACKEND": "wagtail_localize.tasks.DjangoRQJobBackend", "OPTIONS": {"QUEUE": "default"}, } ``` -------------------------------- ### Configure Translatable URLs with i18n_patterns Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/2-configure-wagtail-localize.md This Python code snippet configures translatable URL paths for a Django project using i18n_patterns. It includes the search path and Wagtail's main URL patterns, ensuring they are prefixed with language codes. ```Python from django.conf.urls.i18n import i18n_patterns\n\n\n# These paths are translatable so will be given a language prefix (eg, '/en', '/fr')\urlpatterns = urlpatterns + i18n_patterns(\n path("search/", search_views.search, name="search"),\n # For anything not caught by a more specific rule above, hand over to\n # Wagtail's page serving mechanism. This should be the last pattern in\n # the list:\n path("", include(wagtail_urls)),\n # Alternatively, if you want Wagtail pages to be served from a subpath\n # of your site, rather than the site root:\n # path("pages/", include(wagtail_urls)),\n) ``` -------------------------------- ### Configure Custom Job Backend in Wagtail Localize Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/configure-background-tasks.md This snippet illustrates how to configure Wagtail Localize to use a custom job backend. It specifies the path to the custom backend class and any associated options. ```python WAGTAILLOCALIZE_JOBS = { "BACKEND": "python.path.to.MyJobBackend", "OPTIONS": { # Any options can go here }, } ``` -------------------------------- ### Generate SSH Keypair Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/pontoon.md Generates a new SSH keypair for Wagtail Localize to authenticate with a Git repository. The command `ssh-keygen` is used, and it's recommended to leave the passphrase blank. ```shell ssh-keygen -f wagtail-localize-key -C wagtail-localize ``` -------------------------------- ### Configure Google Cloud Translation with Environment Variable Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Sets up Wagtail Localize to use Google Cloud Translation when the GOOGLE_APPLICATION_CREDENTIALS environment variable is configured. Only the project ID needs to be specified in the settings. ```Python WAGTAILLOCALIZE_MACHINE_TRANSLATOR = { "CLASS": "wagtail_localize.machine_translators.google.GoogleCloudTranslator", "OPTIONS": { "PROJECT_ID": "", }, } ``` -------------------------------- ### Enable Wagtail's Internationalisation Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/tutorial/2-configure-wagtail-localize.md This Python code snippet demonstrates how to enable Wagtail's internationalization by setting WAGTAIL_I18N_ENABLED to True. It also includes Django's USE_I18N and USE_L10N settings. ```Python USE_I18N = True\n\nUSE_L10N = True # only if using Django < 4.0\n\n# Add this\nWAGTAIL_I18N_ENABLED = True\n\nUSE_TZ = True ``` -------------------------------- ### Custom Machine Translator Integration Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Demonstrates how to create a custom machine translator by subclassing Wagtail Localize's BaseMachineTranslator. It includes methods for defining the display name, performing translations (handling HTML or plain text), and checking translation capabilities between locales. ```python from .base import BaseMachineTranslator class CustomTranslator(BaseMachineTranslator): display_name = "Custom translator" def translate(self, source_locale, target_locale, strings): return { string: StringValue.from_translated_html( translate_html(string.get_translatable_html()) ) for string in strings } def can_translate(self, source_locale, target_locale): return source_locale.language_code != target_locale.language_code ``` -------------------------------- ### Run Specific Tox Test Case Source: https://github.com/wagtail/wagtail-localize/blob/main/README.md Executes a particular test case within a specified tox environment. This is useful for debugging or focusing on a specific test. ```Shell tox -e python3.13-django5.2-wagtail7.0-sqlite -- wagtail_localize.tests.test_edit_translation.TestGetEditTranslationView ``` -------------------------------- ### Template Segment Structure (HTML) Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/concept/segments.md Demonstrates the HTML structure of a Template Segment, showing how text content is replaced with `` tags to mark insertion points for translated strings. ```html

``` -------------------------------- ### Set GOOGLE_APPLICATION_CREDENTIALS Environment Variable Source: https://github.com/wagtail/wagtail-localize/blob/main/docs/how-to/integrations/machine-translation.md Configures Google Cloud authentication for Wagtail Localize by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the service account key file. This allows the Python client to automatically find the credentials. ```Bash GOOGLE_APPLICATION_CREDENTIALS="/path/to/keyfile.json" ```