我的Django应用程序中在线登录用户的问题

时间:2017-09-14 13:56:53

标签: django django-models django-views django-users

一如既往,我正在努力改进我的Django application,我想创建一个可以display all logged users的Django模块。

这是我的模型类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)

然后,我认为:

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)

print query返回:[]

一个非常简单的模板,只是为了显示已登录的用户:

{% block content %}

List of logged users :

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

{% endblock %}

问题是:当我尝试在我的软件上连接不同的帐户时,表LoggedUser仍为空。我的剧本是否犯了错误?

1 个答案:

答案 0 :(得分:1)

可能你的连接没有连接到Django信号

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)