Categories
Python

Django Bootstrap alert Closeable

In this post we are going to create a new base.html file which will handle the bootstrap and the most important django messages to display in alert div. We send error or success messages from the backend code using standard messages api and in the front end we display that messages using the bootstrap alert class.

Here is the complete code for base.html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blockchain Voting System</title>
    <!-- Include Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- Include Toastr CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
    <!-- Add your custom styles if needed -->
    <style>
        .cta-btn {
            margin-top: 30px;
        }

       
    </style>

</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'login' %}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'register' %}">Register</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'landing_page' %}">Home</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>


    <main>
        {% if messages %}
        <div class="alert alert-danger alert-dismissible fade show">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <ul class="list-unstyled">
                {% for message in messages %}
                <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>
                    {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}<strong>Important:</strong> {% endif %}
                    {{ message }}
                    </li>
                    {% endfor %}
            </ul>
        </div>
        {% endif %}

        <!-- Content specific to each page goes here -->
        {% block content %}
        {% endblock %}
    </main>

    <!-- Bootstrap JS and Toastr JS -->
    <!-- Include Bootstrap JS and Toastr JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>



</body>

</html>Code language: HTML, XML (xml)

Auto Close Alert after timeout

We can also add a JavaScript function to with setTimeOut to close the alert after sometime. Here is the complete code for closing the alert div after some time. In that code we are simply waiting for the document to get ready then we use setTimeout function inside that we use jquery to select our div with id and then we use close to simply close the alert div.

<script>
    // Automatically dismiss the alert after 5 seconds (5000 milliseconds)
    $(document).ready(function () {
      setTimeout(function () {
        $("#error-alert").alert('close');
      }, 3000);
    });
  </script>
Code language: HTML, XML (xml)

Make use of Warning, Info and Error alerts

When we pass the alert with message in django we pass, message.error, message.info, message.warning and message.success. We can customize the code to adopt this change and show the respective class and message inside that alert div. Here is the code which do this.

<div>
    {% if messages %}
    <div class="alert-container">
      {% for message in messages %}
      <div
        class="alert alert-dismissible fade show {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}alert-danger{% elif message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}alert-success{% elif message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}alert-warning{% elif message.level == DEFAULT_MESSAGE_LEVELS.INFO %}alert-info{% endif %}"
        role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <ul class="list-unstyled">
          <li>
            {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}<strong>Error:</strong> {% endif %}
            {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}<strong>Success:</strong> {% endif %}
            {% if message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}<strong>Warning:</strong> {% endif %}
            {% if message.level == DEFAULT_MESSAGE_LEVELS.INFO %}<strong>Info:</strong> {% endif %}
            {{ message }}
          </li>
        </ul>
      </div>
      {% endfor %}
    </div>
    {% endif %}
  </div>

Code language: HTML, XML (xml)

Here is how we pass the message to the template in django.

from django.contrib import messages
from django.shortcuts import render

def my_view(request):
    # Your view logic here whatever you want to implement
    # Add a success message
    messages.success(request, 'This is a success message.')
    # or you can show the error message with this
    messages.error(request, 'This is a Error message.')

    return render(request, 'your_template.html')
Code language: Python (python)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.