Geolocation of Client with Django

My first thoughts yesterday when I started trying to add a lookup for a user’s country based on IP address was that this was going to be tricky. I figured I would have to create some models, fill them with data fixtures and do some manual queries against the database.

Turns out it was fairly trivial to do.

Django comes with some handy modules for doing it all for you. It just requires installing a C library from MaxMind and downloading their free Country data file.

To install the GeoIP MaxMind C Lib on Mac I used homebrew

brew install geoip

on the server I had to do the same thing on Linux:

sudo yum install geoip

Then I downloaded the free country data file from MaxMind and put it in my django project’s ‘geo’ directory:

$ curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
$ gunzip GeoIP.dat.gz 
$ mv GeoIP.dat <project_root>/geo/</project_root>

To finish the setup I needed to add a line to the settings.py file:

import os
PROJECT_ROOT = os.path.dirname(__file__)
GEOIP_PATH = os.path.join(PROJECT_ROOT, 'geo')

Getting the country of a connecting user was then rather simple.

from django.contrib.gis.utils import GeoIP
g = GeoIP()
country = g.country_code(request.META['REMOTE_ADDR'])

For the complete documentation on GeoIP check out the official documentation.