TheDeadMays
TheDeadMays

Reputation: 81

How to show user status (Online, Offline) in Django 1.9?

I am trying to make a "social" site, where you can add friends, create posts, etc. So the main problem is, how to show user status, using Django Admin API?

Thanks in advance!

In html:

{{ user.is_authenticated }}

In view:

def index(request):
    user = User.objects.get(username="root")
    return render(request, 'blog/index.jade', {'users': users})

So this basically returns me True or False, but this is the status not for only "root" user, but anyone.

Upvotes: 2

Views: 2394

Answers (2)

Kaushal Kumar
Kaushal Kumar

Reputation: 1306

Make Ajax request every 5 seconds which will be handled by view. And on each request update table column last_active corresponding to that user which will update the timestamp (you have to make a last_active column of timestamp type).

Make another Ajax request every 5 seconds to fetch all the users who are online by comparing current time and last_active timestamp corresponding to each user. It will return all the users online.

You can use this logic to make multiuser/singleuser chat system also.

Code for making Ajax request:

(function getOnline() {

    $.ajax({
        url: '/get_online', 
        type: "GET",
        data:
        {
            user:user
        },
        success: function(data) {
          console.log("success");
        },
        complete: function() {
          // Schedule the next request when the current one is complete
          setTimeout(getOnline, 5000);
        },
        error: function(xhr, errmsg, err) {
                 console.log("error");
        }
    });
})();

Upvotes: 2

tklodd
tklodd

Reputation: 1079

You won't be using the Django admin page for that - that is just for database management. What you are referring to with {{ user.is_authenticated }} is part of the Django templating system. That is a variable that is written to the page on page load. It will not change until the user reloads the page. What you're going to need to do is use javascript's setInterval function to routinely do an ajax call back to the server. So you have a js file with an initialization function that calls the setInterval function, which in turn makes an ajax call every 20 seconds or so. The ajax call goes to a url that is defined in your urls.py file, which associates it with a view that is defined in your views.py file. That view queries the database to see if a user is authenticated or not, and then it returns that info in an HttpResponse to your ajax call, which has a callback that saves the response to an object, which you then render to the page in whatever way you want, to let the user know that other users are or are not logged in.

Upvotes: 0

Related Questions