[Django]-Django message once logged in

10👍

Use django’s messaging framework and wrap the login view:

from django.contrib import messages
from django.contrib.auth.views import login

def custom_login(request,*args, **kwargs):
    response = login(request, *args, **kwargs):
    if request.user.is_authenticated():
         messages.info(request, "Welcome ...")
    return response

and in your template somewhere:

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

along with some jquery to hide any message after 5 seconds:

$(document).ready(function(){
    $('.messages').delay(5000).fadeOut();
});

6👍

Note that you can use the user_logged_in signal to add the message when the user logs in, instead of wrapping the login view, as pastylegs does in his answer.

# include this code somewhere it will be imported when the application loads
from django.contrib import messages
from django.contrib.auth.signals import user_logged_in

def logged_in_message(sender, user, request, **kwargs):
    """
    Add a welcome message when the user logs in
    """
    messages.info(request, "Welcome ...")

user_logged_in.connect(logged_in_message)

You then display the message and use javascript in the same way as pastyleg’s answer.

Leave a comment