DEV Community

DoriDoro
DoriDoro

Posted on

Django messages framework

Introduction:

The Django framework already provides all the necessary implementations to enable the messages framework. The default settings created by using django-admin startproject already contain all the settings needed to enable message functionality.

You can find django.contrib.messages in INSTALLED_APPS in your settings.py configuration file.

The necessary middleware will also be added: django.contrib.sessions.middleware.SessionMiddleware and django.contrib.messages.middleware.MessageMiddleware. The default storage backend relies on sessions, so the SessionMiddleware must be enabled.

And at last the context_processors option of the DjangoTemplates backend defined in your settings.py configuration file contains django.contrib.messages.context_processors.messages.


In order to customise the message tags and to use the message alerts of Bootstrap 5.3, the variable MESSAGE_TAGS is overwritten in the following way:

# settings.py

from django.contrib.messages import constants as messages


# for django messages framework:
MESSAGE_TAGS = {
    messages.DEBUG: "alert-secondary",
    messages.INFO: "alert-info",
    messages.SUCCESS: "alert-success",
    messages.WARNING: "alert-warning",
    messages.ERROR: "alert-danger",
}
Enter fullscreen mode Exit fullscreen mode

Create a template that iterates over the messages and displays them as needed to display them on your website.

# messages.html

<div class="mt-4" style="width: 95%; padding-top: 40px;">
  {% if messages %}
    <ul class="messages">
      {% for message in messages %}
        <div class="container-fluid p-0">
          <div class="alert {{ message.tags }} alert-dismissible" role="alert" >
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            {{ message }}
          </div>
        </div>
      {% endfor %}
    </ul>
  {% endif %}
</div>

Enter fullscreen mode Exit fullscreen mode

Due to the Bootstrap implementation, this template is customised.


You will need to add the messages.html ({% include 'messages.html' %}) template to the base layout because I have created a separate messages template.

# base.html

 <!-- End of Navbar -->

 <!-- Alert/Messages -->
 {% include 'messages.html' %}
 <!-- End of Alert/Messages -->

 {% block content %}
 {% endblock %}
Enter fullscreen mode Exit fullscreen mode

I have chosen to display the messages under the navbar and before the block content of the website.


The last important part is to create messages in your view. If you don't create any messages (error, info, success, etc) in your view, you won't see any messages.

# views.py

from django.contrib import messages

def login_page_view(request):
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password'],
            )
            if user is not None:
                login(request, user)
                return redirect('review:feeds_page')

            else:
                messages.error(request, "Invalid username or password!")

    return render(request, 'login_page.html', context={'form': form})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)