Show logged users - keeping track of users login and logout

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
models.py
"""
from django.db import models
from django.contrib.auth.signals import user_logged_in, user_logged_out  

class LoggedUser(models.Model):
  username = models.CharField(max_length=30, primary_key=True)
  
  def __unicode__(self):
    return self.username

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

def logout_user(sender, request, user, **kwargs):
  try:
    u = LoggedUser.objects.get(pk=user.username)
    u.delete()
  except LoggedUser.DoesNotExist:
    pass
    
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)


"""
This is an example view in views.py that shows all logged users
"""
from django.shortcuts import render_to_response
from django.template import RequestContext
from usuarios.models import LoggedUser

def logged(request):
  logged_users = LoggedUser.objects.all().order_by('username')
  return render_to_response('users/logged.html',
                            {'logged_users': logged_users},
                            context_instance=RequestContext(request))

More like this

  1. login on activation with django-registration by morgan 4 years, 1 month ago
  2. Auto Logout Middleware by LuckiDog 6 years, 6 months ago
  3. Email or username authentication with masquerading by petrilli 4 years, 10 months ago
  4. Login + logout script from a nub by alandelevie 5 years, 4 months ago
  5. Auth decorators with 403 by Magus 6 years, 11 months ago

Comments

arthur (on September 5, 2012):

Wouldn't it be better to just query the Django sessions? That would be session backend specific though.

I don't think the above code works with multi-process wsgi workers.

#

albertorcf (on September 6, 2012):

I tested the code in production (webfaction/apache2/django1.4.1) and it didn't work very well. Using the developer server everything goes the right way.

I will move the logged users list to the database and test again. If it works ok, I will update the code.

#

albertorcf (on September 6, 2012):

I moved the user logged list to the database and now it seems to be working properly. I tested in a WebFaction with Apache server, mod_wsgi 3.4, Python 2.7 installed and running Django 1.4 with an extremely low load.

#

(Forgotten your password?)