diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py index b51e292aa0..1198689968 100644 --- a/django/contrib/messages/storage/cookie.py +++ b/django/contrib/messages/storage/cookie.py @@ -14,6 +14,10 @@ class MessageEncoder(json.JSONEncoder): """ message_key = '__json_message' + def __init__(self, *args, **kwargs): + kwargs.setdefault('separators', (',', ':')) + super().__init__(*args, **kwargs) + def default(self, obj): if isinstance(obj, Message): # Using 0/1 here instead of False/True to produce more compact json @@ -148,7 +152,7 @@ class CookieStorage(BaseStorage): also contains a hash to ensure that the data was not tampered with. """ if messages or encode_empty: - encoder = MessageEncoder(separators=(',', ':')) + encoder = MessageEncoder() value = encoder.encode(messages) return self.signer.sign(value) diff --git a/django/contrib/messages/storage/session.py b/django/contrib/messages/storage/session.py index 170c4940ab..b5291f151c 100644 --- a/django/contrib/messages/storage/session.py +++ b/django/contrib/messages/storage/session.py @@ -38,7 +38,7 @@ class SessionStorage(BaseStorage): return [] def serialize_messages(self, messages): - encoder = MessageEncoder(separators=(',', ':')) + encoder = MessageEncoder() return encoder.encode(messages) def deserialize_messages(self, data): diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py index 5d5fb42d67..7f4672de8b 100644 --- a/tests/messages_tests/test_cookie.py +++ b/tests/messages_tests/test_cookie.py @@ -141,7 +141,7 @@ class CookieTests(BaseTests, SimpleTestCase): }, Message(constants.INFO, 'message %s'), ] - encoder = MessageEncoder(separators=(',', ':')) + encoder = MessageEncoder() value = encoder.encode(messages) decoded_messages = json.loads(value, cls=MessageDecoder) self.assertEqual(messages, decoded_messages) @@ -166,7 +166,7 @@ class CookieTests(BaseTests, SimpleTestCase): storage = self.storage_class(self.get_request()) messages = ['this', 'that'] # Encode/decode a message using the pre-Django 3.1 hash. - encoder = MessageEncoder(separators=(',', ':')) + encoder = MessageEncoder() value = encoder.encode(messages) encoded_messages = '%s$%s' % (storage._legacy_hash(value), value) decoded_messages = storage._decode(encoded_messages)