Django: Remove duplicate messages from storage
django, django-messages, django-middleware
Solution
Ran into the same problem and found another solution, using a custom MESSAGE_STORAGE:
from django.contrib.messages.storage.session import SessionStorage
from django.contrib.messages.storage.base import Message
class DedupMessageMixin(object):
def __iter__(self):
msgset = [tuple(m.__dict__.items())
for m in super(DedupMessageMixin, self).__iter__()]
return iter([Message(**dict(m)) for m in set(msgset)])
class SessionDedupStorage(DedupMessageMixin, SessionStorage):
pass
# in settings
MESSAGE_STORAGE = 'some.where.SessionDedupStorage'
This will work fine with code that would also play with messages directly, say in a view for example. Since it's a mixin, you can easily reuse it for other message storages.
Here is an alternative to avoid storing duplicates at all:
from django.contrib.messages.storage.session import SessionStorage
from itertools import chain
class DedupMessageMixin(object):
def add(self, level, message, extra_tags):
messages = chain(self._loaded_messages, self._queued_messages)
for m in messages:
if m.message == message:
return
return super(DedupMessageMixin, self).add(level, message, extra_tags)
Problem
I'm using `messages` to add flash messages to the template (just as you'd expect). The problem I have is that if you double click a link to a page that generates a message then the message appears twice. I am using the message to tell the user I have redirected them from where they were expecting to go. They don;t need the same message twice. I understand the logic here but am wondering how I can remove duplicated messages. - click url - message generated, saved in storage - click url again before page renders - second message generated, saved in storage - response adds all messages from storage - renders with two messages Ultimately I would like this to be a `middleware` so it can cover off all requests.