<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Django on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/django/</link>
    <description>Recent content in Django on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Sat, 05 Apr 2014 21:46:42 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/django/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Django Country Context</title>
      <link>https://mpcabd.xyz/django-country-context/</link>
      <pubDate>Sat, 05 Apr 2014 21:46:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/django-country-context/</guid>
      <description>&lt;p&gt;This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.</p>
<h2 id="using-the-context">Using The Context</h2>
<p>To use the country context</p>
<ol>
<li>You activate the country of choice when you start to process the request, one place for activating the country is by writing a <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/" title="Middleware | Django documentation | Django" target="_blank">Django middleware</a> that activates the country in the <code>process_request</code> method.</li>
<li>After that your code should depend on the <code>country_context.get_current_country_code</code> to get the current country code, and that should be everywhere, so that you don’t have to pass the current country from the view to the controllers and to other parts of your code.</li>
<li>In the end when you finish processing the request you should deactivate the country, also you can do that in the middleware in the <code>process_response</code> method.</li>
</ol>
<p>If you want to create a middleware you can extend the <code>CountryContextMiddleware</code> included with this package.</p>
<h2 id="settings">Settings</h2>
<p>You should have the following two variables:</p>
<ol>
<li><code>DEFAULT_COUNTRY</code>: The default country code that will be the active country by default.</li>
<li><code>ENABLED_COUNTRIES</code>: A list of country codes that are enabled for your site. Codes are in <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" target="_blank">ISO 3166-1 Alpha 2</a> format.</li>
</ol>
<h2 id="example-usage">Example Usage</h2>
<p>We will imagine a Django site, an e-commerce site that serves multiple stores in US and UK, by default it’ll be serving the US site, but if the URL was prefixed with UK then the site will serve the UK store.</p>
<pre class="lang:python decode:true"># site/settings.py
# ...
DEFAULT_COUNTRY = 'US'
ENABLED_COUNTRIES = ['US', 'UK']
# ...
MIDDLEWARE_CLASSES = (
  # ...
  'site.country_context_middleware.SiteCountryContextMiddleware',
  # ...
)
</pre>
<pre class="lang:python decode:true"># site/country_context_middleware.py
import re

from django_country_context.country_context_middleware import CountryContextMiddleware


class SiteCountryContextMiddleware(CountryContextMiddleware):
  def get_country_code_from_request(self, request):
    if re.match(r'^/UK/', request.path_info, re.I):
      return 'UK'
    return 'US'
</pre>
<pre class="lang:python decode:true"># site/urls.py

from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
  url(r'^(?:%s)?/' % '|'.join(
    ''.join(
      '[%s%s]' % (c.upper(), c.lower()) for c in country
    ) for country in settings.ENABLED_COUNTRIES
  ), include('app.urls')),
)
</pre>
<pre class="lang:python decode:true"># app/models.py

from django.db import models
from django_country_context import country_context, countries_data


class StoreManager(models.Manager):
  def __init__(self, countries_enabled=True):
    super(StoreManager, self).__init__()
    self.countries_enabled = countries_enabled

  def get_query_set(self):
    qs = super(StoreManager, self).get_query_set()
    if self.countries_enabled:
      qs = qs.filter(country=country_context.get_current_country_code())
    return qs


class Store(models.Model):
  # ...
  country = models.CharField(max_length=2, default=country_context.get_current_country_code, choices=countries_data.ENABLED_COUNTRIES_TUPLE, db_index=True)

  objects = StoreManager()
  objects_no_countries = StoreManager(countries_enabled=False)
</pre>
<pre class="lang:python decode:true"># app/admin.py

from django.contrib import admin
from models import Store


class StoreAdmin(admin.ModelAdmin):
  model = Store
  def queryset(self, request):
    self.model._default_manager = self.model.objects_no_countries
    return super(StoreAdmin, self).queryset(request)
  # ...

admin.site.register(Store, StoreAdmin)
</pre>
<p>Using the setup above will allow the views to call the query the Store model without handling special cases for countries, and you can change the logic of getting the current country without any change to your views, this way we’ve separated the country context completely from the logic of the site. And when you need to get the current country name or code you can use <code>country_context.get_current_country_name()</code> and <code>country_context.get_current_country_code()</code> respectively. Please note that the setup above was written for a Django 1.4.x.</p>
<h2 id="download">Download</h2>
<p><a href="https://github.com/mpcabd/django-country-context/">Django Country Context on source code on GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>How to make django management commands send errors email to admins</title>
      <link>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</link>
      <pubDate>Sun, 08 Dec 2013 13:15:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</guid>
      <description>&lt;p&gt;I usually use django’s &lt;a title=&#34;Writing custom django-admin commands&#34; href=&#34;https://docs.djangoproject.com/en/dev/howto/custom-management-commands/&#34; target=&#34;_blank&#34;&gt;custom management commands&lt;/a&gt; to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I usually use django’s <a title="Writing custom django-admin commands" href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/" target="_blank">custom management commands</a> to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg" rel="lightbox[403]" title="How to make django management commands send errors email to admins"><img class="aligncenter size-medium wp-image-404" alt="Django's error email sample" src="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg" width="300" height="207" srcset="https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg 300w, https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg 996w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>You can of course log all the commands you run and the cron jobs you have in files, but the problem is that sometimes you need to be notified instantly via your email, so here’s how to make django management commands send you the errors email.</p>
<h2 id="understanding-how-django8217s-error-email-works">Understanding how django’s error email works</h2>
<p>If you check django’s logging documentation you will find that it has a built-in handler called <a href="https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.AdminEmailHandler" title="Django Logging AdminEmailHandler" target="_blank">AdminEmailHandler</a> this handler sends an email to the site admins for each log message it receives.</p>
<p>So basically all you need to do is to tell your django commands to log the errors using a logger with that handler, and you’ll receive the emails.</p>
<p>To do so define a logger in your <code>settings.py</code>:</p>
<pre class="lang:python decode:true">LOGGING = {
    #OTHER OPTIONS
    'filters': {
        #OTHER FILTERS
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        #OTHER HANDLERS
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        }
    },
    'loggers': {
        #OTHER LOGGERS
        'management_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
</pre>
<p>And after that in your custom commands log the errors you face using the logger you defined:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
from django.core.management.base import BaseCommand
import sys

logger = getLogger('management_commands')

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            #DO YOUR STUFF HERE
        except Exception as e:
            logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            #Raise the exception again so it gets logged in standard error also.
            raise e
</pre>
<h2 id="enabling-the-logger-to-all-commands-in-one-configuration">Enabling the logger to all commands in one configuration</h2>
<p>You can also make all the commands (custom or not) send the error by email by editing <code>manage.py</code> almost the same way as we edited the command file above:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
import sys

logger = getLogger('management_commands')

#Wrap this line with a try-catch execute_from_command_line(sys.argv)
    try:
        execute_from_command_line(sys.argv)
    except Exception as e:
        logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
        raise e
</pre>
<p>This way all the commands will send the error by email also to django admins.</p>
<p>Enjoy it!</p>]]></content:encoded>
    </item>
    <item>
      <title>Python Celery Asynchronous Task Decorator</title>
      <link>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</link>
      <pubDate>Wed, 10 Oct 2012 20:58:02 +0000</pubDate>
      <guid>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</guid>
      <description>&lt;p&gt;A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.&lt;/p&gt;
&lt;p&gt;Executing asynchronous tasks in Python can be made in multiple ways, one of them is using &lt;a href=&#34;http://celeryproject.org/&#34; title=&#34;Celery: Distributed Task Queue&#34; target=&#34;_blank&#34;&gt;celery&lt;/a&gt;, a distributed task queue written in Python which has proved itself to be a great solid task queue system.&lt;/p&gt;
&lt;p&gt;And if you’re using Django then there is a Django app to make your life easier, &lt;a href=&#34;https://github.com/celery/django-celery/&#34; title=&#34;Celery integration for Django&#34; target=&#34;_blank&#34;&gt;django-celery&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.</p>
<p>Executing asynchronous tasks in Python can be made in multiple ways, one of them is using <a href="http://celeryproject.org/" title="Celery: Distributed Task Queue" target="_blank">celery</a>, a distributed task queue written in Python which has proved itself to be a great solid task queue system.</p>
<p>And if you’re using Django then there is a Django app to make your life easier, <a href="https://github.com/celery/django-celery/" title="Celery integration for Django" target="_blank">django-celery</a>.</p>
<p>Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.</p>
<p>So let’s get started!</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/10/celery-python.png"/> 
</figure>

<h3 id="description">Description</h3>
<p>The following code will allow you to decorate Python functions with a decorator that will allow them to be executed asynchronously in a seamless easy way. You don’t have to change any thing in your code, just add the <code>asynchronous_task</code> decorator to the functions you want them to be executed asynchronously and you’re done.</p>
<p>This code can be used with Django also, just uncomment the Django block in it and it’ll work.</p>
<p>I wrote this code in a file called <code>celery_tasks.py</code> which probably the place you’ll have your all celery tasks, it adds a task called <code>execute</code> that is responsible for executing the passed function and parameters.</p>
<pre class="lang:python decode:true">import os, sys
from celery.task import task

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, os.path.dirname(__file__))

##########################
# Uncomment the following code block to enable it to work with Django.
# Either put this file next to the settings.py file, or change the block code to import your settings module from the correct path.
##########################

#from django.core.management import setup_environ
#import settings
#setup_environ(settings)

@task(name='execute')
def execute(module_name, method_name, *args, **kwargs):
	try:
		m = __import__(module_name)
		if m.__name__ != module_name:
			modules = module_name.split('.')[1:]
			for module in modules:
				m = getattr(m, module)
		f = getattr(m, method_name)
		if hasattr(f, 'func'):
			f = f.func
		return f(*args, **kwargs)
	except Exception, e:
		raise e
</pre>
<p>The code looks like a mess I know, but simply what it does is that you pass this task the following parameters:</p>
<ol>
<li>Python module name to get the function from</li>
<li>Method name to be executed</li>
<li>Positional and named parameters</li>
</ol>
<p>The second part is defining the decorator, lets assume that this file is called <code>celery_decorator.py</code>:</p>
<p><strong>Note that I’m assuming that <code>celery_decorator.py</code> is in the same folder of your <code>celery_tasks.py</code> file.</strong></p>
<pre class="lang:python decode:true">from django.utils.decorators import available_attrs
from django.utils.functional import wraps

def asynchronous_task(check_if_active = False):
	def wrapper(f):
		try:
			@wraps(f, assigned=available_attrs(f))
			def _wrapper(*args, **kwargs):
				try:
					if check_if_active:
						from celery.task.control import inspect
						insp = inspect()
						d = insp.active()
						if not d:
							raise Exception
					from celery_tasks import execute
					execute.delay(f.__module__, f.func_name, *args, **kwargs)
				except Exception as e:
					f(*args, **kwargs)
			_wrapper.func = f
			return _wrapper
		except Exception:
			return f
	return wrapper
</pre>
<p>This decorator simply wraps the function in a call to the <code>execute</code> task on celery, so that it’ll be executed asynchronously, it accept an optional parameter that defines whether the decorator should check if celery is running and if it’s not then execute the function synchronously, it is set to <code>False</code> by default because it takes some time to check celery, so it makes the performance poor a little bit.</p>
<p>Now we can us it on any function inside our code:</p>
<pre class="lang:python decode:true">from celery_decorator import asynchronous_task

#Default not to check if celery is running
@asynchronous_task
def a_very_long_process(p1, p2):
    pass #TODO: Do something

#Force check
@asynchronous_task(check_if_active = True)
def another_very_long_process(p1, p2):
    pass #TODO: Do something
</pre>
<p>Now in your code you just simply don’t change anything, all the calls to these two functions will be asynchronous calls.</p>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download a copy of <code>celery_tasks.py</code> and <code>celery_decorators.py</code> from this Gist: <a href="https://gist.github.com/3874979">https://gist.github.com/3874979</a></p>
<p>Hope this helps somebody to perform faster 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Get Online Users in Django</title>
      <link>https://mpcabd.xyz/get-online-users-in-django/</link>
      <pubDate>Mon, 21 Sep 2009 22:41:00 +0000</pubDate>
      <guid>https://mpcabd.xyz/get-online-users-in-django/</guid>
      <description>&lt;p&gt;I was upgrading my &lt;a href=&#34;http://mpcabd.alwaysdata.net/&#34; target=&#34;_blank&#34;&gt;Django Bookmarks&lt;/a&gt; site, and I wanted to list the online users. I searched the internet and I found a &lt;a href=&#34;http://www.djangosnippets.org/snippets/947/&#34; target=&#34;_blank&#34;&gt;simple method&lt;/a&gt;, but it doesn’t work properly. So I developed my own method.&lt;/p&gt;
&lt;h1 id=&#34;why-the-simple-method-didnt-work&#34;&gt;Why the simple method didn’t work?&lt;/h1&gt;
&lt;p&gt;The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.&lt;/p&gt;
&lt;p&gt;Imagine the following scenario:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The user X logs in @ 1:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 1:30 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comments on a previous post @ 1:35 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X leaves the website @ 1:40 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comes back to the website @ 3:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X is logged in since the session cookie has not expired yet.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 3:15 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A guest enters the website, and looks at the online users corner.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was upgrading my <a href="http://mpcabd.alwaysdata.net/" target="_blank">Django Bookmarks</a> site, and I wanted to list the online users. I searched the internet and I found a <a href="http://www.djangosnippets.org/snippets/947/" target="_blank">simple method</a>, but it doesn’t work properly. So I developed my own method.</p>
<h1 id="why-the-simple-method-didnt-work">Why the simple method didn’t work?</h1>
<p>The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.</p>
<p>Imagine the following scenario:</p>
<ul>
<li>
<p>The user X logs in @ 1:00 pm.</p>
</li>
<li>
<p>The user X posts a new post @ 1:30 pm.</p>
</li>
<li>
<p>The user X comments on a previous post @ 1:35 pm.</p>
</li>
<li>
<p>The user X leaves the website @ 1:40 pm.</p>
</li>
<li>
<p>The user X comes back to the website @ 3:00 pm.</p>
</li>
<li>
<p>The user X is logged in since the session cookie has not expired yet.</p>
</li>
<li>
<p>The user X posts a new post @ 3:15 pm.</p>
</li>
<li>
<p>A guest enters the website, and looks at the online users corner.</p>
</li>
</ul>
<p>The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.</p>
<h2 id="update-8th-may-2013">UPDATE 8th May 2013</h2>
<p>Please note the solution provided in this post is an old solution, it is coded in a weird way maybe, and it is not the best way to achieve what is required. I’ll write soon a new solution that in my opinion will be far better than this one.</p>
<h1 id="so-what-is-missing-here">So what is missing here?</h1>
<p>The last login date is not enough to tell if the user online or not, we must have another field that tells us when is the last activity date for the user.</p>
<p>In ASP .NET there is a field called LastActivityDate in the users table, and it is used for this specific mission.</p>
<h1 id="when-to-update-last-activity-date">When to update last activity date?</h1>
<p>In ASP .NET you have to update the last activity manually, and there is a good way to do it; in global.asax:</p>
<pre class="lang:c# decode:true">private void Application_AuthenticateRequest(Object source, EventArgs e) {
    //Your Code Goes Here
}
</pre>
<p>In this method you can access the request, get the current user, update his/her last activity date.</p>
<p>So basically updating last activity date is done on the request, when the user makes a request to your application and he/she is authenticated.</p>
<h1 id="but-there-is-no-last-activity-date-in-djangos-user-model">But there is no last activity date in Django’s user model?</h1>
<p>Yeah I know, but you can extend the User module in Django. And to do this there are many ways, one of them is by making a new model with a foreign key to the User. Then you can do whatever you want.</p>
<h1 id="and-where-am-i-going-to-write-the-code-that-will-update-the-last-activity-date">And where am I going to write the code that will update the last activity date?</h1>
<p>In Django we have <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" target="_blank">Middleware</a>; a Middleware is a layer that handles something on each request, its input is the request and it can process it or modify it.</p>
<p>So I simply created a new Middleware that takes the request and finds the user, then updates his/her last activity.</p>
<p>I installed the middleware in the settings module, I appended its name after ‘django.contrib.auth.middleware.AuthenticationMiddleware’ in MIDDLEWARE_CLASSES.</p>
<p>There was a problem in doing that, because the user might send many request per page, each image will send a request, and imagine how many updates there is in each page!</p>
<p>The solution is to skip a list of URLs, so if the user requests a URL within this list his/her last activity date won’t be updated. The skip list is stored within the urls.py file.</p>
<p>The skip list will contain regular expressions just like the url_patterns dictionary.</p>
<h1 id="making-the-solution-generic">Making the solution generic</h1>
<p>I wanted to publish this solution, and it had to be generic so you can use it without editing its code.</p>
<p>Making it generic required small modifications:</p>
<ul>
<li>
<p>Making a new application called lastActivityDate.</p>
</li>
<li>
<p>Pasting the extended user model inside models.py.</p>
</li>
<li>
<p>Modifying the settings module and add lastActivityDate to the INSTALLED_APPS list.</p>
</li>
</ul>
<h1 id="extending-the-user-module">Extending the user module</h1>
<pre class="lang:python decode:true">from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class UserActivity(models.Model):
    last_activity_ip = models.IPAddressField()
    last_activity_date = models.DateTimeField(default = datetime(1950, 1, 1))
    user = models.OneToOneField(User, primary_key=True)
</pre>
<p>Since the User and UserActivity models are now related one-to-one we can now type:</p>
<pre class="lang:python decode:true">a = User.objects.get(username__exact='mpcabd')
print a.useractivity.last_activity_ip

b = UserActivity.objects.get(user=a)
print b.user.username
</pre>
<h1 id="the-middleware">The Middleware</h1>
<pre class="lang:python decode:true">from models import UserActivity
from datetime import datetime
from django.conf import settings
from django.contrib.sites.models import Site
import re

compiledLists = {}

class LastActivityMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return
        urlsModule = __import__(settings.ROOT_URLCONF, {}, {}, [''])
        skipList = getattr(urlsModule, 'skip_last_activity_date', None)
        skippedPath = request.path
        if skippedPath.startswith('/'):
            skippedPath = skippedPath[1:]
        if skipList is not None:
            for expression in skipList:
                compiledVersion = None
                if not compiledLists.has_key(expression):
                    compiledLists[expression] = re.compile(expression)
                compiledVersion = compiledLists[expression]
                if compiledVersion.search(skippedPath):
                    return
        activity = None
        try:
            activity = request.user.useractivity
        except:
            activity = UserActivity()
            activity.user = request.user
            activity.last_activity_date = datetime.now()
            activity.last_activity_ip = request.META['REMOTE_ADDR']
            activity.save()
            return
        activity.last_activity_date = datetime.now()
        activity.last_activity_ip = request.META['REMOTE_ADDR']
        activity.save()
</pre>
<p>The compiled list is for enhancing performance, each regular expression is compiled one time; when it is accessed the first time.</p>
<p>You can see that I used the settings module to get a the URLs module name. And I used the __import__ function to import the module dynamically.</p>
<p>In line 12 I check if there is a list called ‘skip_last_activity_date’ using the getattr function, passing a third parameter to this functions specifies the default value if the list was not found so I don’t get an exception.</p>
<p>In lines 25 to 37 I get or create the UserActivity object, I update the last activity date using datetime.now(), I update the last activity IP using request.META[‘REMOTE_ADDR’] which gives me the client IP address.</p>
<h1 id="modifying-the-urls-module">Modifying the URLs module</h1>
<p>In the urls.py file insert the following code:</p>
<pre class="lang:python decode:true">skip_last_activity_date = [
    #Your expressions go here
]
</pre>
<h1 id="modifying-the-settings-module">Modifying the settings module</h1>
<p>In the settings.py file insert the following code:</p>
<pre class="lang:python decode:true">#Your settings code
MIDDLEWARE_CLASSES = (
    #Your middleware classes go here
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'lastActivityDate.LastActivityMiddleware.LastActivityMiddleware',
    #Your middleware classes go here
)
#Your settings code
INSTALLED_APPS = (
    #Your installed apps
    'YOUR_APP_FOLDER.lastActivityDate',
    #Your installed apps
)
#Your settings code
</pre>
<p>Replace YOUR_APP_FOLDER with the folder of your application, such that the directory tree is like this:</p>
<pre class="decode:true">YourAppFolder:
--&gt; appFolder
--&gt; …
--&gt; __init__.py
--&gt; views.py
--&gt; models.py
--&gt; …
--&gt; lastActivityDate
--&gt; __init__.py
--&gt; LastActivityMiddleware.py
--&gt; models.py
--&gt; urls.py
--&gt; settings.py
--&gt; __init__.py
--&gt; manage.py
</pre>
<h1 id="ps">P.S.</h1>
<p>Do not forget to synchronize the database using “manage.py syncdb” so that Django creates the lastactivitydate_useractivity table in the database.</p>
<h1 id="getting-online-users">Getting online users</h1>
<p>After this long trip here is how to get online users:</p>
<pre class="lang:python decode:true">from django.contrib.auth.models import User
from datetime import datetime, timedelta
from lastActivityDate.models import UserActivity

def get_online_users(num):
    fifteen_minutes = datetime.now() - timedelta(minutes=15)
    sql_datetime = datetime.strftime(fifteen_minutes, '%Y-%m-%d %H:%M:%S')
    users = UserActivity.objects.filter(last_activity_date__gte=sql_datetime, user__is_active__exact=1).order_by('-last_activity_date')[:num]
    return [u.user for u in users]
</pre>
<p>This function returns a list of users whose last activity was in the last 15 minutes. Of course you can modify it and expand the duration.</p>
<h1 id="download-source-code">Download source code</h1>
<p>Here is the link to download source code of the lastActivityDate application:</p>
<p><a href="http://www.box.net/shared/1prdvejycg" target="_blank">lastActivityDate.tar.gz</a></p>
<p>Notice that the code is written using Python 2.6 and Django 1.0. If you have different version(s) you <strong>might</strong> encounter a problem.</p>
<h1 id="license">License</h1>
<p>This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License.</p>
<p>To view a copy of this license, visit <a href="http://creativecommons.org/licenses/by-sa/3.0/">http://creativecommons.org/licenses/by-sa/3.0/</a>.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
