It is most important to keep the users of your web application aware of what’s going on makes a big difference in the user experience. There’s one thing users hate over slow applications, it is applications that don’t communicate with them.

– The user clicks in a save button.
– Nothing happens.
– So, did it save the data or not?
– User reaction after a couple of (mili) seconds: Clicking save button several times

Let’s make our users more confident and comfortable, shall we?

Configuration

A brand new Django project by default comes with the messages framework installed. If you haven’t changed anything related to the messages framework, just skip the below settings for the messages framework to the next section. Otherwise, set it up:

INSTALLED_APPS

django.contrib.messages 

MIDDLEWARE or MIDDLEWARE_CLASSES in older versions:

django.contrib.sessions.middleware.SessionMiddleware
django.contrib.messages.middleware.MessageMiddleware 

TEMPLATES

context_processors
django.contrib.messages.context_processors.messages

Message Levels and Tags

ConstantLevelTag (for CSS)Purpose
DEBUG10debugDevelopment-related messages that will be ignored (or removed) in a production deployment
INFO20infoInformational messages for the user
SUCCESS25successAn action was successful
WARNING30warningA failure did not occur but may be imminent
ERROR40errorAn action was not successful or some other failure occurred

Django will only display messages with a level greater than 20 (INFO) by default. If you want to display DEBUG messages:

from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG 

Or if you are running into circular imports, you can add the constant value directly:

MESSAGE_LEVEL = 10  # DEBUG 

Usage

See the below example:

Views.py

In views.py Import messages from django.contrib and add a message in user_form.is_valid() section of the code as shown below:

from django.contrib import messages

class ProfileUpdateView(LoginRequiredMixin, TemplateView):
    user_form = UserForm
    profile_form = ProfileForm
    template_name = 'common/profile-update.html'

    def post(self, request):

        post_data = request.POST or None
        file_data = request.FILES or None

        user_form = UserForm(post_data, instance=request.user)
        profile_form = ProfileForm(post_data, file_data, instance=request.user.profile)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Your profile is updated successfully!')
            return HttpResponseRedirect(reverse_lazy('profile'))

        context = self.get_context_data(
                                        user_form=user_form,
                                        profile_form=profile_form
                                    )

        return self.render_to_response(context)     

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs) 

Base.html

Include the HTML file path in the main content section where we are going to write the HTML for messages:

 <!-- Main Content -->
      <div id="content">

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

        {% block content %}  {% endblock content %}
        
      </div>
 <!-- End of Main Content --> 

Messages.html

Now in messages.html we are going to display messages and have set id=”msg” in div tag: django messages bootstrap alert

{% if messages %}
    {% for message in messages %}
        <div class="alert {{ message.tags }} m-2" id="msg" role="alert">
            {{ message }}
        </div>
    {% endfor %}
{% endif %} 

Settings.py

In settings.py we are importing message constants:

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',
}

Base.html

In Base.html we are writing a script to set the time if the message id is having the length greater than 0, then we will remove the message after 2000 milliseconds i.e. 2 seconds.

 <script>
    setTimeout(function(){
      if ($('#msg').length > 0) {
        $('#msg').remove();
      }
    }, 2000)
  </script> 

There you go, once you click on the update button you will get a success message similarly you can do for other methods like Warning, error, info, debug, etc. )

Built-in methods:

Some Examples –

messages.debug(request, 'Total records updated {0}'.format(count))
messages.info(request, 'Improve your profile today!')
messages.success(request, 'Your password was updated successfully!')
messages.warning(request, 'Please correct the error below.')
messages.error(request, 'An unexpected error occured.')

# Or...

messages.add_message(request, messages.DEBUG, 'Total records updated {0}'.format(count))
messages.add_message(request, messages.INFO, 'Improve your profile today!')

# Useful to define custom levels:
CRITICAL = 50
messages.add_message(request, CRITICAL, 'A very serious error ocurred.') 

Tags- django messages, django message framework, django messages framework,
from django.contrib import messages, message framework django,
django messages success, how to use django messages, messages framework django, import messages in django,