The Messages Framework - 30 days of Django

The Messages Framework - 30 days of Django

/ #Django


Django comes with a cool message framework which let's us use session to show messages to the user.

Let's say that we want to show a message to the user when he or she adds a task. How do we do that? Well, the most simple way would be to use Django's built in messages framework.

If you open up settings.py, you'll notice that it's already added to the list of INSTALLED_APPS.

So let's open up the task/views.py and do some changes:

from django.contrib import messages # New, 1
...

@login_required
def frontpage(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)

        if form.is_valid():
            form.save()

            messages.success(request, 'The task was added', extra_tags='is-success') # New, 2
    else:
        form = TaskForm()

    title = 'This is a variable'
    tasks = Task.objects.filter(user=request.user)
    categories = Category.objects.all()

    page = request.GET.get('page', 1)
    paginator = Paginator(tasks, 10)
    try:
        tasks = paginator.page(page)
    except PageNotAnInteger:
        tasks = paginator.page(1)
    except EmptyPage:
        tasks = paginator.page(tasks.num_pages)

    return render(request, 'task/frontpage.html', {'title': title, 'tasks': tasks, 'categories': categories, 'form': form})

So we didn't add more than 2 lines, but it's everything we need in the backend.
1: First, we import the method from Django.
2: Then, we add a new message to the session after the task is gone.

We specify the text and also add a optional parameter called "extra_tags". This is not necessary, but I want to do it to get some styling from Bulma.

Django has a lot of other options for the messages. If you want to learn more about them, you can read it here: https://docs.djangoproject.com/en/4.0/ref/contrib/messages/

Great, let's open up the base.html file and show the messages there:

...

<nav class="navbar is-dark">
    ...
</nav>

{% if messages %}
    {% for message in messages %}
        <div class="notification {{ message.tags }}">{{ message }}</div>
    {% endfor %}
{% endif %}

...

So here we check if there are any messages, and if there are, we loop through them. The {{ message.tags }} is the "extra_tags".

So when the message is added to the system (in views.py), it's waiting to be shown. And as soon as it's shown, it will not appear again. So if you refresh, the message is gone :-)

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.