Software Solutions Company

Django Messages

Jan. 8, 2023
Author: Asif Shahzad | Full Stack Web Developer


Here I will show the procedure to display message when form is submited. After 5 second the message will disappear. Lets start!

1. Add in Setting.py

INSTALLED_APPS = [
    
    'django.contrib.messages',
   
]

For bootstrap message formates add this code in setting.py

from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
        messages.DEBUG: 'alert-secondary',
        messages.INFO: 'alert-info',
        messages.SUCCESS: 'alert-success',
        messages.WARNING: 'alert-warning',
        messages.ERROR: 'alert-danger',
}

This will show colouful alerts

2. Set up message template

{% for message in messages %}
<div class="container-fluid">
  <div id ="alert" 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 }}
  </div>
</div>
{% endfor %}


<script type="text/javascript">
    setTimeout(function () {

        // Closing the alert
        $('#alert').alert('close');
    }, 5000);
</script>

Here at the at the bottom, scripts hide the message after 5 seconds.

3. Include Message Template

Include Message Template in Django Form where required at top or bottom.

{% include 'main/messages.html' %}

4. In views.py add success and error

if form.is_valid():
            form.save()
            messages.success(request, 'Contact request submitted successfully.')
            
        else:
            messages.error(request, 'Invalid form submission.')
            messages.error(request, form.errors)

 

That's it.

Check the alerts.

Please share this page to friends.

Asif Shahzad | Full Stack Web Developer

Welcome to our Software Solutions Company, where we excel in transforming ideas into tangible realities. We have expertise in developing online management systems, website designing & development, software solutions, mobile app development, e-commerce solutions and graphic designing. We provide 24/7 services.

Popular Posts






Call To Action

Do you Need a website?

Order Now