Login

Show logged users - keeping track of users login and logout

Author:
albertorcf
Posted:
September 5, 2012
Language:
Python
Version:
1.4
Score:
2 (after 2 ratings)

Showing a list of logged users using the user_logged_in and user_logged_out signals.

See login and logout signals in Django docs.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.

#

Please login first before commenting.