djangobootstrap-4messagetoast

Django messages + bootstrap toast. How to make it work?


Trying to get bootstrap popup and django messages to work. The problem is that I do not understand how to do it correctly so that if there is a message in the context, it would be displayed in the upper right part of the site.

Documentation: https://getbootstrap.com/docs/4.3/components/toasts/

Django v3.1.6 and Bootstrap v4.5

In the static files of the project there is bootstrap.bundle.js, it is also included in the base template. I'm not good at django in layout, so I will be very grateful for the most detailed answer.


Solution

  • You can modify the message classes shown in your template using MESSAGE_TAGS setting.

    Add this to your settings.py

    MESSAGE_TAGS = {
        messages.DEBUG: 'alert-info',
        messages.INFO: 'alert-info',
        messages.SUCCESS: 'alert-success',
        messages.WARNING: 'alert-warning',
        messages.ERROR: 'alert-danger',
    }
    

    Then display them in your template (preferably at your base template)

    {% for message in messages %}
        <div class="alert {{ message.tags }} alert-dismissible shadow fade show" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            {{ message | safe }}
        </div>
    {% endfor %}