From bdee9ff5b906f682cfc8c4a774074a8b2aacf463 Mon Sep 17 00:00:00 2001 From: Hugo Defrance Date: Wed, 15 May 2024 14:50:41 +0200 Subject: [PATCH] Feat: Add build_lang helper in utils --- AUTHORS.rst | 1 + modeltranslation/tests/tests.py | 7 +++++++ modeltranslation/utils.py | 8 ++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index 8a0e70de..f60e7cd5 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -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 diff --git a/modeltranslation/tests/tests.py b/modeltranslation/tests/tests.py index adf2701c..555b1ed4 100644 --- a/modeltranslation/tests/tests.py +++ b/modeltranslation/tests/tests.py @@ -33,6 +33,7 @@ from modeltranslation.utils import ( auto_populate, build_css_class, + build_lang, build_localized_fieldname, fallbacks, ) @@ -1182,6 +1183,12 @@ def test_indonesian(self): 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 diff --git a/modeltranslation/utils.py b/modeltranslation/utils.py index 2023ccd3..e00f3551 100644 --- a/modeltranslation/utils.py +++ b/modeltranslation/utils.py @@ -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: