Sometimes we need to show the one-time notification, also known as the flash messages in our Django application. For this Django provides the messages framework. We are going to use the same here.
To show flash messages in the Django application, we will extend our previous project Hello World in Django 2.2. Clone the git repository, check out the master branch and set up the project on your local machine by following the instructions in the README file.
Paste the below code snippet in the body tag of HTML file hw/templates/hw/home.html
.
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message | safe }}
</div>
{% endfor %}
Define the messages constant. Paste the below code snippet in settings.py
file.
try:
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
except Exception as e:
pass
In your view file, import the messages package.
from django.contrib import messages
Now inside the home view, set the appropriate message in request.
def home(request):
data = dict()
messages.success(request, "Success: This is the sample success Flash message.")
messages.error(request, "Error: This is the sample error Flash message.")
messages.info(request, "Info: This is the sample info Flash message.")
messages.warning(request, "Warning: This is the sample warning Flash message.")
return render(request, 'hw/home.html', data)
Refresh the home page in your browser.
Source Code:
Source code is available on GitHub. Checkout the branch flash_messages.
In case of any query, feel free to comment.