Search code examples
djangodjango-messages

How can I count the messages coming from a view inside a template?


I'm using Django's messages framework to pass messages from my view functions to my templates. I want a template to contain some HTML only if the number of messages is greater than 1. Is there a way to do this?

I've tried the following:

{% if messages.count > 1 %}

    <html for multiple messages>

{% else %}

    <html for just one message>

{% endif %}

But messages.count doesn't seem to exist.


Solution

  • messages has a __len__ function, so it can be used with the length template filter:

    {% if messages|length > 1 %}
    
        <html for multiple messages>
    
    {% else %}
    
        <html for just one message>
    
    {% endif %}
    

    See https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#length