Showing flash messages in DJango with close button

Question:

I want to display flash messages in Django with the close button.
Existing message framework in Django allows to display messages and does not allow to close it.

As an example, web2py provides such flash messages. I am looking for similar functionality in Django.

Flash Message in web2py

If it can be done with few lines of code , it would be great.
I do not want to add any other libraries or framework on top of Django.

Thanks in advance.

Asked By: Utsav Chokshi

||

Answers:

I was unaware that such thing can be solved using boot-strap !

I did something like this :

{% if messages %}
  {% for msg in messages %}
    <div class="alert alert-info alert-dismissable">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
      {{msg.message}}
    </div>
  {% endfor %}
{% endif %}

It shows message like :
Flash Message in Django

Answered By: Utsav Chokshi

in html template add this jquery timeout function

<script>
    $(document).ready(function(){
window.setTimeout(function() {
  $(".alert").fadeTo(500, 0).slideUp(500, function(){
      $(this).remove();
  });
}, 5000);
});
</script>
Answered By: Thameem

Q. Dismiss Button is not working in alert message in django python

Ans:
data-bs-dismiss="alert" ,this is the change in Bootstrap 5 i.e. in another bootstrap version there is data-dismiss="alert" , but in bootstrap 5 there is bs added so add bs like this
data-bs-dismiss="alert"

Answered By: Sandy

If you are using materializecss you can take the help of chip

 <div class="chip" style="display: contents;">
    <div class="card-panel red darken-1 ">
        <i class="material-icons white-text">info</i>
        <span class="white-text text-darken-2" style="vertical-align: super; font-size: large;">
            {{message}}
        </span>
       <i class="close material-icons white-text right">close</i>
    </div>
</div>

enter image description here

If you are using bootstrap 5 use this.

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields below.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

In older versions of bootstrap if you have
data-dismiss="alert"
change this to

data-bs-dismiss="alert"

for more docs visit bootstrap 5 Dismissing

Answered By: jeevu94

As @jeevu94 pointed out correctly, I would suggest using it in a more DRY way that fits each message’s setup.

{% if messages %}

{% for message in messages %}

<div class="container-fluid p-0">
  <div class="alert {{ message.tags }} alert-dismissible" role="alert" >
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="x"></button>
    {{ message }}
  </div>
</div>

{% endfor %}

{% endif %}
Answered By: mika