Django: Remove message before they are displayed

12,120

Solution 1

For the sake of resolution I'm going to mark the method I went with as "The Answer". Thanks to those who commented.

I went with this:

storage = messages.get_messages(request)
storage.used = True

Because it seemed cleaner, was easier to test, and conformed with the general practices of the rest of the project.

Solution 2

I like this simpler approach for clearing out the underlying iterator, since I actually wanted to add a new message in the place of a standard Django message.

list(messages.get_messages(request))

Solution 3

I had to use 2 of the solutions proposed above toghether as no one alone was enought:

storage = messages.get_messages(request)
for _ in storage: 
    pass

if len(storage._loaded_messages) == 1: 
    del storage._loaded_messages[0]

As far as the accepted solution I can loop over the messages several time and I see that the messages don't seem to be "consumed"

Solution 4

For me in Django 1.5 and session message storage accepted method dit not the trick.

I needed to use:

storage = messages.get_messages(request)
for _ in storage:
    pass

To get rid of messages from storage.

Solution 5

If your logout view always redirects to a "logout page", then you can just change your logout template to hide your messages.

e.g., in template:

{% block extra-header %}
<style type="text/css">
    #message-id { display: none; }
</style>
{% endblock %}

It feels a little 'hacky' but I think it's certainly less hacky than your #2.

Share:
12,120
IntrepidDude
Author by

IntrepidDude

Updated on June 16, 2022

Comments

  • IntrepidDude
    IntrepidDude almost 2 years

    I know this question sounds weird, but please, let me explain myself.

    I'm using a decorator to make a message persist until the user actually dismisses it (like the behavior of stack overflow's messages). The problem is, as a result of this, the message gets added before the user signs out, and so the message gets displayed right after the user logs out. I'm wondering what the best way to remove the message in the logout view is. I've thought of two ways to do this, and am wondering if anyone can think of a better one.

    I'm currently favoring this:

    storage = messages.get_messages(request)
    storage.used = True
    

    Over this:

    storage = messages.get_messages(request)
    del storage._loaded_messages[0]
    

    To me the second way seems more explicit, even though it is uglier: my intention is to remove the currently loaded messages and this makes that clear. The first way employs a means by which the messages will be cleared as a side effect ... but at least it doesn't rely upon a dunder variable ... what do you guys think?