Search code examples
djangodjango-messages

Django messages - check if a message already exists before adding


Is it possible to check if a django message and contents exist before adding another message?

In my example I am peforming a try - except in a loop, and if an exception occurs I add a message, but I only want the message to appear once, not for each item in the loop:

for i in data:
    # do something...
    try:
        # try to act upon something
    except:
        # failed action add a message
        if not messages.?.contains("Error: Unable to perform action X")
            messages.add_message(request, messages.ERROR, 'Error: Unable to perform action X')
        pass

Solution

  • You are looking for messages.get_messages(request) method.

    To get the list of all messages, wrap that method call within list constructor:

    all_messages = list(messages.get_messages(request))

    Each message object has information about its level, message itself etc. You can use that fields to check if message you are searching for already exists.

    Simple snippet:

    all_error_messages_content = [msg.message for msg in list(messages.get_messages(request)) if msg.level_tag == 'error']
    if 'Error: Unable to perform action X' not in all_error_messages_content:
         messages.add_message(request, messages.ERROR, 'Error: Unable to perform action X')