Skip to main content
 首页 » 编程设计

python之如何在 Django 1.9 中显示用户状态(在线、离线)

2025年05月04日28tintown

我正在尝试制作一个“社交”网站,您可以在其中添加 friend 、创建帖子等。所以主要问题是,如何使用 Django Admin API 显示用户状态?

提前致谢!

在 html 中:

{{ user.is_authenticated }} 

在 View 中:

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

所以这基本上会返回 True 或 False,但这不仅仅是“root”用户的状态,而是任何人的状态。

请您参考如下方法:

每 5 秒发出一次 Ajax 请求,该请求将由 View 处理。并且在每个请求更新表列 last_active 对应于将更新时间戳的用户(您必须制作时间戳类型的 last_active 列)。

每5秒发起一次Ajax请求,通过比较每个用户对应的当前时间和last_active时间戳来获取所有在线用户。它将返回所有在线用户。

你也可以使用这个逻辑来制作多用户/单用户聊天系统。

Ajax请求代码:

(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"); 
        } 
    }); 
})();