Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting/Clearing django.contrib.messages

Tags:

django

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
like image 766
The Wanderer Avatar asked Mar 02 '17 02:03

The Wanderer


People also ask

How do you delete Django messages?

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.

How do you use contrib messages in Django?

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."

What are messages in Django how it's helping Django application development?

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).


2 Answers

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.

like image 196
fgblomqvist Avatar answered Nov 15 '22 20:11

fgblomqvist


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

like image 27
Avukonke Peter Avatar answered Nov 15 '22 20:11

Avukonke Peter