from django.contrib import messages

{% if messages %}
    {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} {% endfor %}
{% endif %}

Here is what the above code is Doing:
1. We’re checking if there are any messages in the messages variable. If there are, we’ll display them.
2. We’re looping through each message in the messages variable.
3. We’re checking if the message has any tags. If it does, we’ll display them.
4. We’re checking if the message is an error. If it is, we’ll display it as an error.
5. We’re displaying the message.
6. We’re closing the

    tag.
    7. We’re closing the {% if messages %} tag.

    Now, let’s add a message to our view:

    from django.contrib import messages

    def index(request):
    messages.add_message(request, messages.INFO, ‘Hello world!’)
    return render(request, ‘index.html’)

    The first argument is the request object. The second argument is the message level. The third argument is the message.

    The message level is optional. If you don’t specify a message level, the message will be displayed at the default level, which is INFO.

    The message level can be one of the following:

    DEBUG
    INFO
    SUCCESS
    WARNING
    ERROR

    The message will be displayed in the template like this:

    • Hello world!

    You can also add a tag to the message:

    from django.contrib import messages

    def index(request):
    messages.add_message(request, messages.INFO, ‘Hello world!’, extra_tags=’foo’)
    return render(request, ‘index.html’)

    The message will be displayed in the template like this:

    • Hello world!

    You can also add multiple tags to the message:

    from django.contrib import messages

    def index(request):
    messages.add_message(request, messages.INFO, ‘Hello world!’, extra_tags=’foo bar’)
    return render(request, ‘index.html’)

    The message will be displayed in the template like this: