From fc0f7f6c152766c92a95c74a02cc6fab79440ed8 Mon Sep 17 00:00:00 2001 From: dbxnr Date: Fri, 8 May 2020 09:25:54 +0200 Subject: [PATCH] Fixed #31157 -- Fixed displaying read-only JSONField values in admin. --- django/contrib/admin/utils.py | 5 +++++ tests/admin_utils/tests.py | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index e4ddc8f017..021a086e65 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -398,6 +398,11 @@ def display_for_field(value, field, empty_value_display): return formats.number_format(value) elif isinstance(field, models.FileField) and value: return format_html('{}', value.url, value) + elif isinstance(field, models.JSONField) and value: + try: + return field.get_prep_value(value) + except TypeError: + return display_for_value(value, empty_value_display) else: return display_for_value(value, empty_value_display) diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py index 0ce18be094..cf0d3e064e 100644 --- a/tests/admin_utils/tests.py +++ b/tests/admin_utils/tests.py @@ -179,6 +179,20 @@ class UtilsTests(SimpleTestCase): display_value = display_for_field(None, models.JSONField(), self.empty_value) self.assertEqual(display_value, self.empty_value) + def test_json_display_for_field(self): + tests = [ + ({'a': {'b': 'c'}}, '{"a": {"b": "c"}}'), + (['a', 'b'], '["a", "b"]'), + ('a', '"a"'), + ({('a', 'b'): 'c'}, "{('a', 'b'): 'c'}"), # Invalid JSON. + ] + for value, display_value in tests: + with self.subTest(value=value): + self.assertEqual( + display_for_field(value, models.JSONField(), self.empty_value), + display_value, + ) + def test_number_formats_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12345.6789')