From 0a9522b423270b39ea37bce1bcb481b8a0d443b5 Mon Sep 17 00:00:00 2001 From: Jacob Wegner Date: Mon, 1 Jul 2024 08:40:48 -0500 Subject: [PATCH] Add JSONField support (#119) refs: #118 --- modeltrans/fields.py | 2 +- tests/app/models.py | 10 ++++++++++ tests/test_models.py | 18 ++++++++++++++++++ tests/test_translating.py | 1 + 4 files changed, 30 insertions(+), 1 deletion(-) diff --git a/modeltrans/fields.py b/modeltrans/fields.py index 5e27d6d..04da6f3 100644 --- a/modeltrans/fields.py +++ b/modeltrans/fields.py @@ -13,7 +13,7 @@ get_translated_field_label, ) -SUPPORTED_FIELDS = (fields.CharField, fields.TextField) +SUPPORTED_FIELDS = (fields.CharField, fields.TextField, JSONField) DEFAULT_LANGUAGE = get_default_language() diff --git a/tests/app/models.py b/tests/app/models.py index 62102ca..c461c15 100644 --- a/tests/app/models.py +++ b/tests/app/models.py @@ -52,6 +52,16 @@ def __str__(self): return self.title +class TaggedBlog(models.Model): + title = models.CharField(max_length=255) + tags = JSONField(null=True, blank=True, default=list) + + i18n = TranslationField(fields=("title", "tags")) + + def __str__(self): + return self.title + + class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) diff --git a/tests/test_models.py b/tests/test_models.py index 35bb934..57f2eae 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -12,6 +12,7 @@ ChallengeContent, ChildArticle, NullableTextModel, + TaggedBlog, TextModel, ) from .utils import CreateTestModel @@ -119,6 +120,23 @@ def test_fallback_getting_TextField(self): with override("fr"): self.assertEqual(m.description_i18n, DESCRIPTION) + def test_fallback_getting_JSONField(self): + m = TaggedBlog.objects.create(title="Falcon", tags=["bird", "raptor"]) + with override("de"): + # tags_de is not set, return fallback + self.assertEqual(m.tags_i18n, ["bird", "raptor"]) + + m = TaggedBlog.objects.create(title="Falcon", tags_fr=[]) + with override("fr"): + # tags_fr is set, return the empty list + self.assertEqual(m.tags_i18n, []) + + m = TaggedBlog.objects.create(title="Falcon", tags_fr=None) + with override("fr"): + # tags_fr is set to None, return field default (which is + # an empty list) + self.assertEqual(m.tags_i18n, []) + def test_creating_using_virtual_default_language_field(self): m = Blog.objects.create(title_en="Falcon") diff --git a/tests/test_translating.py b/tests/test_translating.py index e586f10..f3281b7 100644 --- a/tests/test_translating.py +++ b/tests/test_translating.py @@ -34,6 +34,7 @@ def test_get_translated_models(self): expected = { app_models.Article, app_models.Blog, + app_models.TaggedBlog, app_models.ChildArticle, app_models.Category, app_models.Person,