[Solved]-Deleting/Clearing django.contrib.messages

14👍

A one-liner would look like this:

list(messages.get_messages(request))

It essentially performs the same task as @Avukonke Peter’s solution. However, I didn’t find it necessary to set the messages as used (I believe this is done by default, but feel free to correct me if I’m wrong). It’s beyond me why there’s no messages.clear() function.

12👍

You need to iterate through the messages for your current set of messages as retrieved from the ‘get_messages’ method. You can use this code anywhere you want to clear the messages before setting new ones or where you want to simply clear all messages.

system_messages = messages.get_messages(request)
for message in system_messages:
    # This iteration is necessary
    pass

Note: If you do not want to clear messages, then set the system_messages.used flag to ‘False’ as the messages are marked to be cleared when the storage instance is iterated (and cleared when the response is processed).
Reference: https://docs.djangoproject.com/en/3.0/ref/contrib/messages

2👍

This is the only thing (other than overriding the messages block in the template) that worked for me in Django 4.*:

from django.contrib.messages.storage import default_storage
request._messages = default_storage(request)

This is basically re-initialising the storage (like the messages middleware does).

1👍

I am on Django 3.2 and none of the answers given here worked for me. Don’t know why. Maybe it might be due to some changes in the newer versions. So I figured out a way to do this. If you need to delete the messages or you don’t want to show the messages on a certain template, just iterate over the messages without doing anything in the template file.

{% if messages %}
    {% for message in messages %}
    {% endfor %}
{% endif %}

I added these lines in the template in which the messages should be deleted. Doing this in views is not possible now I guess. Still looking up for more insights on this by the community.

Leave a comment