I want to conditionally clear django.contrib.messages
. None of the solutions discussed in these two questions work:
Delete all django.contrib.messages
Django: Remove message before they are displayed
Any suggestions on how I can clear the messages? I am using django 1.10
Code:
messages = get_messages(request)
for msg in messages:
pass
for msg in messages._loaded:
del msg
for msg in messages._queued_messages:
del msg
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
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.