How to display flash message in django ?
In django, the messages framework allows you to temporarily store messages and it is automatically destroyed after it is displayed once.
There are 5 level of displaying messages
- messages.debug(request, '%s SQL statements were executed.' % count)
- messages.info(request, 'Three credits remain in your account.')
- messages.success(request, 'Profile details updated.')
- messages.warning(request, 'Your account expires in three days.')
- messages.error(request, 'Document deleted.')
For more details info, you can visit the documentation here
Now let us see how to use the messages with our example :
Open the views.py file where we had written the code to insert data into database and add the message code as shown below:
def addProduct(request):
form = addProductForm()
if request.method == 'POST':
form = addProductForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Data inserted successfully")
else :
messages.warning(request, "Data was not inserted")
content = {'form':form}
return render(request, 'accounts/addprod.html', content)
To display the message in the add product page, just iterate the messages using a for loop. The messages is like a temporary global storage so you don't have to pass it with the content in the render(). You can print the message as shown below:
{% extends 'accounts/layouts/maintemp.html' %}
{% load static %}
{% block title %}
Add Products
{% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-12">
{% for msg in messages %}
{{msg}}
{% endfor %}
<h1>All Products </h1>
<form action="" method='POST'>
{% csrf_token %}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for x in form %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.name }}</td>
<td>{{ x.price }}</td>
<td>{{ x.category }}</td>
<td>
<a href="{% url 'edit' x.id %}" class="btn btn-primary btn-sm">Edit</a>
<a href="{% url 'delete' x.id %}" class="btn btn-danger btn-sm">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</div>
</div>
</div>
{% endblock content %}
This will display the message in a simple text format. If you are using bootstrap, you can use the alert class for displaying the messages. Below given is a sample code for the bootstrap alert.
{% for msg in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Hey !</strong> {{msg}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}