[Answered ]-How to test for existance of a certain level in django messages

1👍

There isn’t anything built-in. I would suggest writing your own context processor or template tag/filter that extracts the ones with level ERROR. As a filter it might look like this:

@register.filter
def get_errors_only(messages):
    return [message for message in messages if 'error' in message.tags]

Now in the template you can just do:

{% with messages|get_errors_only as error_messages %}
  {% if error_messages %}
     ..
   {% endif %}
{% endwith %}

Don’t forget to load {% load your_custom_templatetags %} module in your template, and update your settings.py to use the extra templatetags as per the docs.

1👍

You can use ifchanged tag:

{% for message in messages %}
    {% if 'error' in message.tags %}
        {% ifchanged 1 %}
            <div id="error-container">
        {% endifchanged %}
    {% endif %}
{% endfor %}

Or, filter messages in view function and pass it to template.

from itertools import islice

def view(request):
    return render(request, 'path/to/template.html', {
        'messages': islice((m for m in messages if 'error' in m.tags), 1),
    })

Leave a comment