Feat: Add build_lang helper in utils

This commit is contained in:
Hugo Defrance 2024-05-15 14:50:41 +02:00 committed by Serhii Tereshchenko
parent d7a4d0b841
commit bdee9ff5b9
3 changed files with 14 additions and 2 deletions

View file

@ -50,6 +50,7 @@ Contributors
* PetrDlouhy
* dmarcelino
* GreyZmeem
* Hugo Defrance
* And many more ... (if you miss your name here, please let us know!)
.. _django-linguo: https://github.com/zmathew/django-linguo

View file

@ -33,6 +33,7 @@ from modeltranslation.tests import models, translation
from modeltranslation.utils import (
auto_populate,
build_css_class,
build_lang,
build_localized_fieldname,
fallbacks,
)
@ -1182,6 +1183,12 @@ class ForeignKeyFieldsTest(ModeltranslationTestBase):
field = models.ForeignKeyModel._meta.get_field("test")
assert field.attname != build_localized_fieldname(field.name, "id")
def test_build_lang(self):
assert build_lang("en") == "en"
assert build_lang("en_en") == "en_en"
assert build_lang("en-en") == "en_en"
assert build_lang("id") == "ind"
class ManyToManyFieldsTest(ModeltranslationTestBase):
@classmethod

View file

@ -51,12 +51,16 @@ def get_translation_fields(field: str) -> list[str]:
return [build_localized_fieldname(field, lang) for lang in settings.AVAILABLE_LANGUAGES]
def build_localized_fieldname(field_name: str, lang: str) -> str:
def build_lang(lang: str) -> str:
if lang == "id":
# The 2-letter Indonesian language code is problematic with the
# current naming scheme as Django foreign keys also add "id" suffix.
lang = "ind"
return str("%s_%s" % (field_name, lang.replace("-", "_")))
return lang.replace("-", "_")
def build_localized_fieldname(field_name: str, lang: str) -> str:
return str("%s_%s" % (field_name, build_lang(lang)))
def _build_localized_verbose_name(verbose_name: Any, lang: str) -> str: