3

I would like to know how to display the greeting message "Welcome User, You are logged in" once the user login and it should vanish within 5 seconds.

The message will be displayed once after the user's successful login but not again on the consecutive visit of the home page during the same session. Because I have taken username in session in the home.html.

Mel
  • 5,837
  • 10
  • 37
  • 42
Raji
  • 551
  • 1
  • 10
  • 23

2 Answers2

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();
});
Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • But where can i customize the message. Default message "You have been signed in" is coming.Please suggest me – Raji Mar 16 '12 at 13:35
  • In the view. You pass the message you want to display in the `messages.info(request, "THIS IS MY MESSAGE")` – Timmy O'Mahony Mar 16 '12 at 13:38
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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516