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.
Add a Django success messagecontrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message. Add a success message just before the return redirect ("main:homepage") stating "Message sent."
For this, Django provides full support for cookie- and session-based messaging, for both anonymous and authenticated users. The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With