Skip to content

Translatable segments models

These models are responsible for storing details about translatable segments within a translation source.

graph TD


A[StringSegment] --> F[TranslationSource]
B[TemplateSegment] --> F
C[RelatedObjectSegment] --> F
A[StringSegment] --> G[TranslationContext]
B[TemplateSegment] --> G
C[RelatedObjectSegment] --> G
A[StringSegment] --> H[String]
B[TemplateSegment] --> I[Template]

style F stroke-dasharray: 5 5
style G stroke-dasharray: 5 5
style H stroke-dasharray: 5 5
style I stroke-dasharray: 5 5

SegmentOverride

Bases: Model

Stores the overridden value of an OverridableSegment.

Some segments are not translatable, but can be optionally overridden in translations. For example, images.

If an overridable segment is overridden by a user for a locale, the value to override the segment with is stored in this model.

Attributes:

Name Type Description
locale ForeignKey to Locale

The Locale to override.

context ForeignKey to TranslationContext

The context to override. With the Locale, this tells us specifically which object/content path to override.

last_translated_by User

The user who last updated this override.

created_at DateTimeField

The date/time when the override was first created.

updated_at DateTimeField

The date/time when the override was last updated.

data_json TextField with JSON contents

The value to override the field with.

has_error BooleanField

Set to True if the value of this overtride has an error. We store overrides with errors in case they were edited from an external system. This allows us to display the error in Wagtail.

field_error TextField

if there was a database-level validation error while saving the translated object, that error is tored here.

Source code in wagtail_localize/models.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
class SegmentOverride(models.Model):
    """
    Stores the overridden value of an OverridableSegment.

    Some segments are not translatable, but can be optionally overridden in translations. For example, images.

    If an overridable segment is overridden by a user for a locale, the value to override the segment with is stored
    in this model.

    Attributes:
        locale (ForeignKey to Locale): The Locale to override.
        context (ForeignKey to TranslationContext): The context to override. With the Locale, this tells us specifically
            which object/content path to override.
        last_translated_by (User): The user who last updated this override.
        created_at (DateTimeField): The date/time when the override was first created.
        updated_at (DateTimeField): The date/time when the override was last updated.
        data_json (TextField with JSON contents): The value to override the field with.
        has_error (BooleanField): Set to True if the value of this overtride has an error. We store overrides with
            errors in case they were edited from an external system. This allows us to display the error in Wagtail.
        field_error (TextField): if there was a database-level validation error while saving the translated object, that
            error is tored here.
    """

    locale = models.ForeignKey(
        "wagtailcore.Locale", on_delete=models.CASCADE, related_name="overrides"
    )
    # FIXME: This should be a required field
    context = models.ForeignKey(
        TranslationContext,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="overrides",
    )
    last_translated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    data_json = models.TextField()
    has_error = models.BooleanField(default=False)

    field_error = models.TextField(blank=True)

    def __str__(self):
        return f"SegmentOverride: {self.locale_id}, {self.context_id}"

    @property
    def data(self):
        return json.loads(self.data_json)

    def set_field_error(self, error):
        """
        Returns a string containing any validation errors on the saved value.

        Returns:
            str: The validation error if there is one.
            None: If there isn't an error.
        """
        self.has_error = True
        # TODO (someday): We currently only support one error at a time
        self.field_error = error[0].messages[0]
        self.save(update_fields=["has_error", "field_error"])

    def get_error(self):
        """
        Returns a string containing any validation errors on the saved value.

        Returns:
            str: The validation error if there is one.
            None: If there isn't an error.
        """
        # Check if a database error was raised when we last attempted to publish
        if self.has_error and self.context is not None and self.field_error:
            return self.field_error

get_error()

Returns a string containing any validation errors on the saved value.

Returns:

Name Type Description
str

The validation error if there is one.

None

If there isn't an error.

Source code in wagtail_localize/models.py
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
def get_error(self):
    """
    Returns a string containing any validation errors on the saved value.

    Returns:
        str: The validation error if there is one.
        None: If there isn't an error.
    """
    # Check if a database error was raised when we last attempted to publish
    if self.has_error and self.context is not None and self.field_error:
        return self.field_error

set_field_error(error)

Returns a string containing any validation errors on the saved value.

Returns:

Name Type Description
str

The validation error if there is one.

None

If there isn't an error.

Source code in wagtail_localize/models.py
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
def set_field_error(self, error):
    """
    Returns a string containing any validation errors on the saved value.

    Returns:
        str: The validation error if there is one.
        None: If there isn't an error.
    """
    self.has_error = True
    # TODO (someday): We currently only support one error at a time
    self.field_error = error[0].messages[0]
    self.save(update_fields=["has_error", "field_error"])

StringSegment

Bases: BaseSegment

Represents a translatable string that was extracted from a TranslationSource.

Attributes:

Name Type Description
string ForeignKey to String

The string that was extracted.

attrs TextField with JSON contents

The HTML attributes that were extracted from the string.

When we extract the segment, we replace HTML attributes with id attributes and the attributes that were removed are stored in this field. When the translated strings come back, we replace the id attributes with the original HTML attributes.

For example, for this segment:

<a href="https://www.example.com">Link to example.com</a>

We will remove the href tag from it and replace it with an id:

<a id="a1">Link to example.com</a>

And then this field will be populated with the following JSON:

{
    "a#a1": {
        "href": "https://www.example.com"
    }
}
source ForiegnKey[TranslationSource]

The source content that the string was extracted from.

context ForeignKey to TranslationContext

The context, which contains the position of the string in the source content.

order PositiveIntegerField

The index that this segment appears on the page.

Source code in wagtail_localize/models.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
class StringSegment(BaseSegment):
    """
    Represents a translatable string that was extracted from a TranslationSource.

    Attributes:
        string (ForeignKey to String): The string that was extracted.
        attrs (TextField with JSON contents): The HTML attributes that were extracted from the string.

            When we extract the segment, we replace HTML attributes with ``id`` attributes and the attributes that were
            removed are stored in this field. When the translated strings come back, we replace the ``id`` attributes
            with the original HTML attributes.

            For example, for this segment:

            ``<a href="https://www.example.com">Link to example.com</a>``

            We will remove the ``href`` tag from it and replace it with an ``id``:

            ``<a id="a1">Link to example.com</a>``

            And then this field will be populated with the following JSON:

            ``` json
            {
                "a#a1": {
                    "href": "https://www.example.com"
                }
            }
            ```

        source (ForiegnKey[TranslationSource]): The source content that the string was extracted from.
        context (ForeignKey to TranslationContext): The context, which contains the position of the string in the source content.
        order (PositiveIntegerField): The index that this segment appears on the page.
    """

    string = models.ForeignKey(
        String, on_delete=models.CASCADE, related_name="segments"
    )
    attrs = models.TextField(blank=True)

    objects = StringSegmentQuerySet.as_manager()

    def __str__(self):
        return f"StringSegment from String({self.string_id})"

    @classmethod
    def from_value(cls, source, language, value):
        """
        Gets or creates a TemplateSegment instance from a TemplateValue object.

        Args:
            source (TranslationSource): The source the template value was extracted from.
            template_value (TemplateValue): The value of the template.

        Returns:
            TemplateSegment: The TemplateSegment instance that corresponds with the given template_value and source.
        """
        string = String.from_value(language, value.string)
        context, context_created = TranslationContext.objects.get_or_create(
            object_id=source.object_id,
            path=value.path,
        )

        segment, created = cls.objects.get_or_create(
            source=source,
            context=context,
            order=value.order,
            string=string,
            attrs=json.dumps(value.attrs, cls=DjangoJSONEncoder),
        )

        return segment

from_value(source, language, value) classmethod

Gets or creates a TemplateSegment instance from a TemplateValue object.

Parameters:

Name Type Description Default
source TranslationSource

The source the template value was extracted from.

required
template_value TemplateValue

The value of the template.

required

Returns:

Name Type Description
TemplateSegment

The TemplateSegment instance that corresponds with the given template_value and source.

Source code in wagtail_localize/models.py
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
@classmethod
def from_value(cls, source, language, value):
    """
    Gets or creates a TemplateSegment instance from a TemplateValue object.

    Args:
        source (TranslationSource): The source the template value was extracted from.
        template_value (TemplateValue): The value of the template.

    Returns:
        TemplateSegment: The TemplateSegment instance that corresponds with the given template_value and source.
    """
    string = String.from_value(language, value.string)
    context, context_created = TranslationContext.objects.get_or_create(
        object_id=source.object_id,
        path=value.path,
    )

    segment, created = cls.objects.get_or_create(
        source=source,
        context=context,
        order=value.order,
        string=string,
        attrs=json.dumps(value.attrs, cls=DjangoJSONEncoder),
    )

    return segment

TemplateSegment

Bases: BaseSegment

Represents a template segment that was extracted from a TranslationSource.

Attributes:

Name Type Description
template ForeignKey to Template

The template that was extracted.

source ForeignKey[TranslationSource]

The source content that the string was extracted from.

context ForeignKey to TranslationContext

The context, which contains the position of the string in the source content.

order PositiveIntegerField

The index that this segment appears on the page.

Source code in wagtail_localize/models.py
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
class TemplateSegment(BaseSegment):
    """
    Represents a template segment that was extracted from a TranslationSource.

    Attributes:
        template (ForeignKey to Template): The template that was extracted.
        source (ForeignKey[TranslationSource]): The source content that the string was extracted from.
        context (ForeignKey to TranslationContext): The context, which contains the position of the string in the source content.
        order (PositiveIntegerField): The index that this segment appears on the page.
    """

    template = models.ForeignKey(
        Template, on_delete=models.CASCADE, related_name="segments"
    )

    def __str__(self):
        return f"TemplateSegment({self.pk}) from Template({self.template_id})"

    @classmethod
    def from_value(cls, source, value):
        """
        Gets or creates a TemplateSegment instance from a TemplateValue object.

        Args:
            source (TranslationSource): The source the template value was extracted from.
            template_value (TemplateValue): The value of the template.

        Returns:
            TemplateSegment: The TemplateSegment instance that corresponds with the given template_value and source.
        """
        template = Template.from_value(value)
        context, context_created = TranslationContext.objects.get_or_create(
            object_id=source.object_id,
            path=value.path,
        )

        segment, created = cls.objects.get_or_create(
            source=source,
            context=context,
            order=value.order,
            template=template,
        )

        return segment

from_value(source, value) classmethod

Gets or creates a TemplateSegment instance from a TemplateValue object.

Parameters:

Name Type Description Default
source TranslationSource

The source the template value was extracted from.

required
template_value TemplateValue

The value of the template.

required

Returns:

Name Type Description
TemplateSegment

The TemplateSegment instance that corresponds with the given template_value and source.

Source code in wagtail_localize/models.py
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
@classmethod
def from_value(cls, source, value):
    """
    Gets or creates a TemplateSegment instance from a TemplateValue object.

    Args:
        source (TranslationSource): The source the template value was extracted from.
        template_value (TemplateValue): The value of the template.

    Returns:
        TemplateSegment: The TemplateSegment instance that corresponds with the given template_value and source.
    """
    template = Template.from_value(value)
    context, context_created = TranslationContext.objects.get_or_create(
        object_id=source.object_id,
        path=value.path,
    )

    segment, created = cls.objects.get_or_create(
        source=source,
        context=context,
        order=value.order,
        template=template,
    )

    return segment

RelatedObjectSegment

Bases: BaseSegment

Represents a related object segment that was extracted from a TranslationSource.

Attributes:

Name Type Description
object ForeignKey to TranslatableObject

The TranslatableObject instance that represents the related object.

source ForeignKey to TranslationSource

The source content that the string was extracted from.

context ForeignKey to TranslationContext

The context, which contains the position of the string in the source content.

order PositiveIntegerField

The index that this segment appears on the page.

Source code in wagtail_localize/models.py
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
class RelatedObjectSegment(BaseSegment):
    """
    Represents a related object segment that was extracted from a TranslationSource.

    Attributes:
        object (ForeignKey to TranslatableObject): The TranslatableObject instance that represents the related object.
        source (ForeignKey to TranslationSource): The source content that the string was extracted from.
        context (ForeignKey to TranslationContext): The context, which contains the position of the string in the source content.
        order (PositiveIntegerField): The index that this segment appears on the page.
    """

    object = models.ForeignKey(
        TranslatableObject, on_delete=models.CASCADE, related_name="references"
    )

    def __str__(self):
        return (
            f"RelatedObjectSegment({self.pk}) from TranslatableObject({self.object_id})"
        )

    def get_source_instance(self):
        return self.object.get_instance_or_none(self.source.locale)

    @classmethod
    def from_value(cls, source, value):
        context, context_created = TranslationContext.objects.get_or_create(
            object_id=source.object_id,
            path=value.path,
        )

        segment, created = cls.objects.get_or_create(
            source=source,
            context=context,
            order=value.order,
            object=TranslatableObject.objects.get_or_create(
                content_type=value.content_type,
                translation_key=value.translation_key,
            )[0],
        )

        return segment

OverridableSegment

Bases: BaseSegment

Represents an overridable segment that was extracted from a TranslationSource.

Attributes:

Name Type Description
data_json TextField with JSON content

The value of the overridable segment as it is in the source.

source ForeignKey to TranslationSource

The source content that the string was extracted from.

context ForeignKey to TranslationContext

The context, which contains the position of the string in the source content.

order PositiveIntegerField

The index that this segment appears on the page.

Source code in wagtail_localize/models.py
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
class OverridableSegment(BaseSegment):
    """
    Represents an overridable segment that was extracted from a TranslationSource.

    Attributes:
        data_json (TextField with JSON content): The value of the overridable segment as it is in the source.
        source (ForeignKey to TranslationSource): The source content that the string was extracted from.
        context (ForeignKey to TranslationContext): The context, which contains the position of the string in the source content.
        order (PositiveIntegerField): The index that this segment appears on the page.
    """

    data_json = models.TextField()

    objects = OverridableSegmentQuerySet.as_manager()

    def __str__(self):
        return f"OverridableSegment({self.pk}) from TranslationSource({self.source_id})"

    @property
    def data(self):
        """
        Returns the decoded JSON data that's stored in .data_json
        """
        return json.loads(self.data_json)

    @classmethod
    def from_value(cls, source, value):
        context, context_created = TranslationContext.objects.get_or_create(
            object_id=source.object_id,
            path=value.path,
        )

        segment, created = cls.objects.get_or_create(
            source=source,
            context=context,
            order=value.order,
            data_json=json.dumps(value.data, cls=DjangoJSONEncoder),
        )

        return segment

data property

Returns the decoded JSON data that's stored in .data_json