Django: Adding user notifications

How to add user notifications with Django messages.

What are Django messages?

Django messages are Django's way of providing our users with notifications after an event or an action.

So, let's get started

Step 1:

First of all, we need to import Django messages in our file, as follows:

from django.contrib import messages

Step 2:

We need to then decide when our Django message must be initiated... In this case our message will be initiated after a user has been registered:


def register(request):

    form = CreateUserForm()

    if request.method == 'POST':

        form = CreateUserForm(request.POST)

        if form.is_valid():

            # - Django messages 
            messages.success(request, "User registration was successful!")

            return redirect("my-login")

    context = {'form':form}

    return render(request, 'register.html', context=context)

Step 3:

Since we are re-directing our user to our login page after they have registered, our Django message will be available for use, on our redirect page, in this case: "my-login".

We need to add the below code to our html template:

Here, we are rendering our message, in this case - "User registration was successful!". We are also checking if our Django message was set to success as we defined in our

   {% for message in messages %}

         {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}

            <p> {{message}} </p>

          {% endif %}

     {% endfor %}

HTML template: "my-login.hml":

<!-- my-login.html -->

{% load static %}

{% load crispy_forms_tags %}



        <meta charset="utf-8" />

        <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1"/>

        <link rel="stylesheet" type="text/css" href="">

        <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">

        <title> Taskly | My Login </title>


    {% include 'pre-base.html' %}


    <div class="container bg-white shadow-md p-5 form-layout">

        <h3> Login </h3>


        <form method="POST" autocomplete="off">

            {% csrf_token %}





            <input class="btn btn-primary navbar-btn" type="submit" value="Login"/>

            <br> <br>

            {% for message in messages %}

                {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}

                    <p> {{message}} </p>

                {% endif %}

            {% endfor %}


            <p> Don't have an account? <a href="{% url 'register' %}"> <br> Register </a> </p>




    <script src="{% static 'js/app.js' %}"></script>

    <script src=""  crossorigin="anonymous"></script>

    <script src=""





Step 4 (optional):

Well done, you are now able to utilize Django messages!

You may want to utilize some CSS or bootstrap to style your notification message, along with JavaScript to set a timer as to how long your message should be visible to users.