[Django]-Displaying a message as a popup/alert in Django?

15👍

This is more a javascript question but anyways, this is how I handle this (if you are using bootstrap):

1) Create a message.html file with the following content:

{% for message in messages %}
  <div class="toast notification bg-{% if message.tags == 'error' %}danger{% else %}{{message.tags}}{% endif %}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
    <div class="toast-header">
      <strong class="mr-auto">
        {% if message.tags == 'error' %}
          <i class="fas fa-times mr-2"></i>
        {% elif message.tags == 'warning' %}
          <i class="fas fa-exclamation mr-2"></i>
        {% elif message.tags == 'info' %}
          <i class="fas fa-info mr-2"></i>
        {% elif message.tags == 'success' %}
          <i class="fas fa-check mr-2"></i>
        {% endif %}
        {{message.tags|capfirst}}
      </strong>
      <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="toast-body">
      {{message|safe}}
    </div>
  </div>
{% endfor %}

2) Change your base.html and add:

...
{% include 'message.html' %}
...


<!-- and at the end:-->
<script src="{% static 'js/jquery-3.4.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% if messages %}
  <script>
      {% for message in messages %}
          $(document).ready(function () {
              $('.toast').toast('show');
          });
      {% endfor %}
  </script>
{% endif %}

Also, don’t forget to include bootstrap.

This way you can use django messages on all of your templates, without explicitly change them.

Edit

You also need this custom css class in order for your notification to show on top right of the page:

.notification{
    position: absolute;
    top: 5rem;
    right: 1rem;
}

0👍

Django has built-in functions for that which is messages.

messages.success(self.request,"message sent")

In your HTML, make sure to create a message class.

{% if message.tags %} class="{{message.tags}}"{% endif %}

Leave a comment