2017-09-14 88 views
0

一如既往,我試圖改進我的Django application,我想創建一個Django模塊,它可以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仍爲空。我在劇本中犯了錯誤嗎?

+0

爲什麼你的信號模型定義 – iklinac

+0

的內部連接@iklinac應該在我看來,功能設置? – Deadpool

+0

這是最好的猜測,但在他們之前刪除縮進:)以便他們在課外 – iklinac

回答

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) 
+0

我必須導入Django信號?因爲'user_logged_in'沒有被定義。 – Deadpool

+0

當然,你需要導入它,更新回答 – iklinac

+0

是的,它的工作原理!非常感謝 ;) – Deadpool

相關問題