diff --git a/django/contrib/messages/storage/base.py b/django/contrib/messages/storage/base.py index 61c5758aab..124049a5e2 100644 --- a/django/contrib/messages/storage/base.py +++ b/django/contrib/messages/storage/base.py @@ -32,6 +32,10 @@ class Message: def __str__(self): return str(self.message) + def __repr__(self): + extra_tags = f", extra_tags={self.extra_tags!r}" if self.extra_tags else "" + return f"Message(level={self.level}, message={self.message!r}{extra_tags})" + @property def tags(self): return " ".join(tag for tag in [self.extra_tags, self.level_tag] if tag) diff --git a/tests/messages_tests/tests.py b/tests/messages_tests/tests.py index d16854a89a..2aa8935474 100644 --- a/tests/messages_tests/tests.py +++ b/tests/messages_tests/tests.py @@ -17,6 +17,35 @@ class MessageTests(SimpleTestCase): self.assertNotEqual(msg_1, msg_3) self.assertNotEqual(msg_2, msg_3) + @override_settings( + MESSAGE_TAGS={ + constants.WARNING: "caution", + constants.ERROR: "", + 12: "custom", + } + ) + def test_repr(self): + tests = [ + (constants.INFO, "thing", "", "Message(level=20, message='thing')"), + ( + constants.WARNING, + "careful", + "tag1 tag2", + "Message(level=30, message='careful', extra_tags='tag1 tag2')", + ), + ( + constants.ERROR, + "oops", + "tag", + "Message(level=40, message='oops', extra_tags='tag')", + ), + (12, "custom", "", "Message(level=12, message='custom')"), + ] + for level, message, extra_tags, expected in tests: + with self.subTest(level=level, message=message): + msg = Message(level, message, extra_tags=extra_tags) + self.assertEqual(repr(msg), expected) + class TestLevelTags(SimpleTestCase): message_tags = {