Issue with online logged users in my Django application

22 views Asked by At

As always, I'm trying to improve my Django application and I would like to create a Django module which could display all logged users.

This is my model class LoggedUser :

class LoggedUser(models.Model):
    user = models.OneToOneField(User, primary_key=True)

    def __unicode__(self):
        return self.user.username

    def login_user(sender, request, user, **kwargs):
        LoggedUser(user=user).save()

    def logout_user(sender, request, user, **kwargs):
        try:
            u = LoggedUser.objects.get(user=user)
            u.delete()
        except LoggedUser.DoesNotExist:
            pass

    user_logged_in.connect(login_user)
    user_logged_out.connect(logout_user)

Then, I have in my view :

def ConnectedUsers(request) :

    logged_users=[user.user for user in LoggedUser.objects.all()]
    print logged_users

    context = {
        "logged_users":logged_users,
    }

    return render(request, "UtilisateursConnectes.html", context)

The print query returns : []

And a very simple template just in order to display logged users :

{% block content %}

List of logged users :

    {% for users in logged_users %} 
        <li>{{ users }}</li>
    {% endfor %}

{% endblock %}

The problem is : When I try to connect different account on my software, the table LoggedUser is still empty. Do I make a mistake in my script ?

1

There are 1 answers

1
iklinac On BEST ANSWER

Probably your connects are not connected to Django signals

from django.contrib.auth.signals import user_logged_in, user_logged_out  

class LoggedUser(models.Model):
    user = models.OneToOneField(User, primary_key=True)

    def __unicode__(self):
        return self.user.username

def login_user(sender, request, user, **kwargs):
        LoggedUser(user=user).save()

def logout_user(sender, request, user, **kwargs):
        try:
            u = LoggedUser.objects.get(user=user)
            u.delete()
        except LoggedUser.DoesNotExist:
            pass

user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)