Hardware, programming and astronomy tutorials and reviews.

Simple site traffic statistics with django-basic-stats

Basic Django site traffic statistic application

django-basic-stats is my basic site traffic statistics application. It can be used to watch latest referrers, Google search terms that led to finding you site or for logging and analyzing mobile devices used to browse your site.


Installation is typical:
pip install django-basic-stats
Next add 'stats' to INSTALLED_APPS and add:
to MIDDLEWARE_CLASSES in your settings.py. You will also have to add:
url(r'^stats/', include('stats.urls'))
to urlpatterns in urls.py.

Last step will be to run manage.py migrate or syncdb if you don't use South migrations.

Statistics are available under /stats/ URL, but only site staff can access them. In admin panel there will be also mobile devices log model with all the data it collected.

Enabling mobile devices logging

Mobile devices aren't logged after installation, as they log screen dimensions and device pixel ratio. Those informations are available in the browser in JavaScript, not in the backend in Python.

To enable mobile device logging use the following JavaScript code. It uses jQuery to send an AJAX request. If you use different library it should be easy to modify this code:

var isMobile = (/iphone|ipod|android|blackberry|mini|palm|smartphone|ipad|xoom|playbook|tablet|mobile|kindle/i.test(navigator.userAgent.toLowerCase()));
if (isMobile) {
        url: '/stats/mobile/',
        cache: false,
        type: "GET",
        data: {"window_width": window.innerWidth,
        "window_height": window.innerHeight,
        "screen_width": screen.width,
        "screen_height": screen.height,
        "device_pixel_ratio": window.devicePixelRatio},

The code sends all the data to "/stats/mobile/" where the Django view will catch them and save. In JavaScript the "window" and "screen" dimensions can differ a lot sometimes so they are both logged. The view will also save the USER_AGENT.

A part of the mobile devices statistics

Django web framework tutorials, 31 July 2013,

Comment article