Fixed #31157 -- Fixed displaying read-only JSONField values in admin.

This commit is contained in:
dbxnr 2020-05-08 09:25:54 +02:00 committed by Mariusz Felisiak
parent 675ce4dd35
commit fc0f7f6c15
2 changed files with 19 additions and 0 deletions

View File

@ -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('<a href="{}">{}</a>', 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)

View File

@ -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')