Connecting Django to a database

This might seem a bit out of order because I blogged about using Django models a few weeks ago but a friend pointed it out to me that some people might actually like to learn how to connect Django to a database in the first place.

Setting up a Django project requires a lot of key pieces to be in place already. Your development environment must already have the following:

  • A working Python installation (2.7+)
  • Python’s pip package installed
  • A clean Django project already setup

I’m not going to explain how to properly setup a Django project. For that, read Jeff Knupp’s excellent post on starting a Django project the Right Way. It might seem like overkill at first to use git, south, virtualenv and fabric for your project. The point is, if your Django project is at all going to be used in production somewhere, then you need to configure these components correctly from the start. On the other hand, if you just want to test something in Django, take only what you need from his blog post and setup the project the way you need.

Right, once you have everything setup and your clean Django project is ready and waiting, you open up your project’s settings.py file. This file contains all references to plugins that your project might use, some language and time settings, and also, the database configuration.

Look for the section called DATABASES and edit it accordingly:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'databaseName',
        'USER': 'databaseUsername',
        'PASSWORD': 'databasePassword',
        'HOST': 'databaseHostname',
    }
}

You could use other databases for your project but I’m using MySQL in this example.

At this point, you can test your connection to the database by running the following from the root of your project directory:

$ python django-admin.py syncdb

If anything goes wrong, like an incorrectly configured username or password, this command will report it.

Another common thing that happens is that the Python MySQL module is not installed. This is where pip comes in:

$ sudo pip install mysql-python

The moment you can run the syncdb command without an error, your Django project is connecting to your database!

Time to setup those data models and get cracking!

As usual, nothing beats the reference documentation, so if you want to learn more about Django and how it connects to databases, check out this link.