Setting up Django with MySQL on OSX

Getting your development environment up when using Django with MySQL might get you errors such as the following which can take up some time

  1. “django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb”which leads to more errors as you go along such as…
  2. EnvironmentError: mysql_config not found
  3. django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/…/django/env/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib

Pre-requisites

Setup Python and virtualenv(optional) & Django

Using MAMP

  1. Download MAMP
  2. Install MySQL from the official website as the headers are need to install mysql-python
  3. nano ~/.bash_profile and add in the following to avoid error 2alias mysql=/Applications/MAMP/Library/bin/mysql
    alias mysql_config=/Applications/MAMP/Library/bin/mysql_config
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
  4. Do a sudo pip install mysql-python
  5. If you do a syncdb command using Django’s manage.py you will get error 3 so do a
    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
  6. Setup your Django project settings.py file database configuration as necessaryFor example,
    DATABASES = {

    ‘default’: {

    ‘ENGINE’: ‘django.db.backends.mysql’,

    ‘NAME’: ‘db_name’,

    ‘USER’: ‘db_user’,

    ‘PASSWORD’: ‘db_pass’,

    ‘HOST’: ‘/Applications/MAMP/tmp/mysql/mysql.sock’,

    ‘PORT’: ‘8889’

    }

    }

Setting up the environment without MAMP

Setting up the environment without MAMP is possible too if you wish to use MySQL together with the workbench for easy administration

  1. Download & install MySQL, Workbench from the official website
  2. nano ~/.bash_profile and add in the following
    alias mysql=/usr/local/mysql/bin/mysql
    alias mysql_config=/usr/local/mysql/lib/mysql_config
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
  3. Do a sudo pip install mysql-python
  4. If you do a syncdb command using Django’s manage.py you will get error 3 so do a
    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
  5. Setup your Django project settings.py file database configuration as necessary

Other Platforms

On Windows, getting the compiled MySQLdb module from Pypi solves the issue rather quickly, otherwise its back to downloading Cygwin and Visual Studio to compile the needed modules.

Linux might have had errors similar or same to error no. 3 which was solved by creating a symbolic link.