[Answer]-Django: 2 active users in a specific url

1👍

You’d have to store who’s at what view in some model.

class UsersInURL(models.Model):
    users = models.ManyToManyField(User)
    url = models.CharField()
    # you'd probably want to use a through table and set up some expiration logic

Then remember to modify this model every time a logged in user views a page; middleware sounds perfect for this.

class UserTrackerMiddleware(object):
    def process_view(self, request, *args, **kwargs):
          UsersInURL.users.through.filter(user=request.user).delete()
          users_in_url, created = UsersInURL.objects.get_or_create(url=request.path)
          users_in_url.users.add(request.user)

Then to refresh their page, you’d need to set some kind of communication between the server and the browser which pings this model and refreshes if it detects some change.

var lastCheckedUsers = undefined;
function checkForNewUsers() {
    $.get('/some-ajaxy-url/', { url: document.URL }, success: function(data) {
         // you'd have to set up a view that returns active users @ url
         if (lastCheckedUsers != data.users && lastCheckedUsers != undefined) {
            window.location.href = window.location.href; 
         };
        lastCheckedUsers = data.users;  // store last state; refresh if modified. 
    })
};
setInterval(checkForNewUsers, 1000);

I’m sure that should get some ideas flowing.

Leave a comment