Setting up Django and SQL Server on Linux

This post is about how to get Django on a Linux box connected to SQL Server. It took me quite a while to get working, so I'm documenting what needs to be done to save other people time.

Installing the right packages

I installed unixODBC-devel, python-devel and freetds via yum. I then install pyodbc with pip, and django-pyodbc from Github. I got my django-pyodbc package from [Lionheart's GitHub Repo](github.com/lionheart/django-pyodbc).

odbcinst.ini file

In order to access the database, you will need the following entries in the odbcinst.ini file:
    [FreeTDS]
    Driver=/usr/lib64/libtdsodbc.so
    Setup=/usr/lib64/libtdsS.so
    UsageCount=1

Checking that you can access the Database

You can use the following command to check that you can see the database
    tsql -H hostname -p port -U username -P password

Getting the Django settings.py file right

Using Lionheart's Github django-pyodbc package, you need to set the Django database *ENGINE* parameter to **"django_pyodbc"**. The *NAME* setting is set to the database name. Set *HOST* to be **"hostname,port"**. Finally, a very important setting is the *OPTIONS* value. This should be set to:
    'OPTIONS' : { 'host_is_server' : True, 'extra_params' : 'TDS_VERSION=8.0', }
The *host_is_server* option tells the django_pyodbc layer to treat the hostname as an actual hostname, rather than a DSN. The *extra_params* option tells the FreeTDS layer to use TDS protocol version 8, which is important otherwise you'll get Unicode errors when you try and communicate with the database.