diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py
index 1d390c71dda..e48d4edb089 100644
--- a/django/contrib/messages/storage/cookie.py
+++ b/django/contrib/messages/storage/cookie.py
@@ -19,7 +19,7 @@ class MessageEncoder(json.JSONEncoder):
# Using 0/1 here instead of False/True to produce more compact json
is_safedata = 1 if isinstance(obj.message, SafeData) else 0
message = [self.message_key, is_safedata, obj.level, obj.message]
- if obj.extra_tags:
+ if obj.extra_tags is not None:
message.append(obj.extra_tags)
return message
return super().default(obj)
diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py
index 53cf693f61c..248afae4f4a 100644
--- a/tests/messages_tests/test_cookie.py
+++ b/tests/messages_tests/test_cookie.py
@@ -52,6 +52,12 @@ class CookieTests(BaseTests, SimpleTestCase):
def stored_messages_count(self, storage, response):
return stored_cookie_messages_count(storage, response)
+ def encode_decode(self, *args, **kwargs):
+ storage = self.get_storage()
+ message = Message(constants.DEBUG, *args, **kwargs)
+ encoded = storage._encode(message)
+ return storage._decode(encoded)
+
def test_get(self):
storage = self.storage_class(self.get_request())
# Set initial data.
@@ -168,12 +174,23 @@ class CookieTests(BaseTests, SimpleTestCase):
A message containing SafeData is keeping its safe status when
retrieved from the message storage.
"""
- def encode_decode(data):
- message = Message(constants.DEBUG, data)
- encoded = storage._encode(message)
- decoded = storage._decode(encoded)
- return decoded.message
+ self.assertIsInstance(
+ self.encode_decode(mark_safe('Hello Django!')).message,
+ SafeData,
+ )
+ self.assertNotIsInstance(
+ self.encode_decode('Hello Django!').message,
+ SafeData,
+ )
- storage = self.get_storage()
- self.assertIsInstance(encode_decode(mark_safe("Hello Django!")), SafeData)
- self.assertNotIsInstance(encode_decode("Hello Django!"), SafeData)
+ def test_extra_tags(self):
+ """
+ A message's extra_tags attribute is correctly preserved when retrieved
+ from the message storage.
+ """
+ for extra_tags in ['', None, 'some tags']:
+ with self.subTest(extra_tags=extra_tags):
+ self.assertEqual(
+ self.encode_decode('message', extra_tags=extra_tags).extra_tags,
+ extra_tags,
+ )