When MySQL is being a pain in the arse…use MariaDB.
I have used Django a few times, and it’s by far the most comprehensive and quick Python web framework out there. I found that the hassle I’ve run into more than once was setting up a database for the Django app. Other things are straightforward to get started.
Getting started with sqlite is fine and is recommended. But what if we want to connect to a more serious relational databases like MySQL? MySQL has become less and less popular, and more are resorting to Postgresql. I have not used MySQL with Django just because it was pretty tedious to set it up and the docs are not at all friendly.
MariaDB is a community-developed fork of MySQL. It is a “drop-in” version of MySQL and can be used interchangeably (Note: Google has recently moved away from MySQL to MariaDB). I’m not going to start up a MariaDB-vs-MySQL death match, but you can read about 10 reasons to move from MySQL to MariaDB.
Without further ado, I’d like to cover a step-by-step guide for dummies to start their first Django + MariaDB project.
Virtualenv
If you have been developing the web with Python for a while, you’d know how valuable virtualenv is. It creates a “clean” environment only for your project and prevent you from having to deal with Python’s global dependencies and installations.
To install virtualenv, on the command line:
$ pip install virtualenv
You might need sudo for root privilege.
Some like to use virtualenvwrapper to manage their environments, but I found it too implicit and confusing for my taste.
Project Directory
Create a workspace directory for your project and a requirements.txt file to keep track of your local installs.
$ mkdir myproject && touch myproject/requirements.txt
Now create a virtual environment for your project
$ cd myproject && virtualenv venv
Note that venv is just a convention. You can name your virtualenv anything. This creates a local copy of Python, setuptools, pip, etc. under the venv directory.
Here is what the workspace looks like
myproject/
├── requirements.txt
└── venv
Within the workspace, activate the virtualenv
$ . venv/bin/activate
You should see this a pair of parentheses enclosing your virtualenv’s name before your command line prompt.
(venv)myproject $
Anything installed with pip will be saved inside venv, not on the system’s Python path.
Install Django and Stuff
Install Django and mysqlclient, the latest driver for MySQL (and MariaDB), then freeze the local installs and write to requirements.txt.
$ pip install Django mysqlclient
$ pip freeze -l > requirements.txt
Start Project
Start a Django project with
$ django-admin startproject myproject
The structure of the project directory looks pretty much like this
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
settings.py will be where we will configure our database adapter. Open the file, and under the database section, edit the config as follow:
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databasesDATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘myproject’,
‘USER’:’yourusername’,
‘PASSWORD’:’yourpassword',
‘HOST’:’localhost’,
‘PORT’:’’,
}
}
Take note of the username and the password since we will be using them to create a project database later.
Install MariaDB
This will be different depending on the platform you’re on. I’m on Mac OSX Yosemite so I’m using Homebrew:
$ brew update
$ brew install mariadb
And the output
$ brew install mariadb
Also installing dependencies: readline
==> Downloading ftp://ftp.cwru.edu/pub/bash/readline-6.2.tar.gz
######################################################################## 100.0%
==> Downloading patches
######################################################################## 100.0%
==> Patching
patching file vi_mode.c
patching file callback.c
==> ./configure --prefix=/usr/local/Cellar/readline/6.2.1 --mandir=/usr/local/Ce
==> make install
==> Caveats
This formula is keg-only, so it was not symlinked into /usr/local.
OS X provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only.
Generally there are no consequences of this for you.
If you build your own software and it requires this formula, you'll need
to add its lib & include paths to your build variables:
LDFLAGS: -L/usr/local/Cellar/readline/6.2.1/lib
CPPFLAGS: -I/usr/local/Cellar/readline/6.2.1/include
==> Summary
/usr/local/Cellar/readline/6.2.1: 32 files, 2.1M, built in 31 seconds
==> Downloading http://ftp.osuosl.org/pub/mariadb/mariadb-5.6.19/kvm-tarbake-jaun
######################################################################## 100.0%
==> ./configure --without-docs --without-debug --disable-dependency-tracking --p
==> make install
==> Caveats
Set up databases with:
unset TMPDIR
mysql_install_db
If this is your first install, automatically load on login with:
cp /usr/local/Cellar/mariadb/5.6.19/com.mysql.mysqld.plist ~/Library/LaunchAgents
launchctl load -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
If this is an upgrade and you already have the com.mysql.mysqld.plist loaded:
launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
cp /usr/local/Cellar/mariadb/5.6.19/com.mysql.mysqld.plist ~/Library/LaunchAgents
launchctl load -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
Note on upgrading:
We overwrite any existing com.mysql.mysqld.plist in ~/Library/LaunchAgents
if we are upgrading because previous versions of this brew created the
plist with a version specific program argument.
Or start manually with:
mysql.server start
Warning: m4 macros were installed to "share/aclocal".
Homebrew does not append "/usr/local/share/aclocal"
to "/usr/share/aclocal/dirlist". If an autoconf script you use
requires these m4 macros, you'll need to add this path manually.
==> Summary
/usr/local/Cellar/mariadb/5.6.19: 231 files, 44M, built in 10.9 minutes
Then, install with
$ unset TMPDIR
$ mysql_install_db
And start the daemon process with
$ cd /usr/local/Cellar/mariadb/5.2.6 ; /usr/local/Cellar/mariadb/5.2.6/bin/mysqld_safe --datadir=/usr/local/var/mysql
Now to start the mariaDB command line, type
$ mysql -uroot
With some luck, you will be greeted with a command prompt:
MySQL [(none)]>
Setup Database & User
To create a new database and user for the Django project, still in MariaDB’s command prompt, type
> CREATE DATABASE myprojectdb;
> CREATE USER ‘myusername’@’localhost’ IDENTIFIED BY ‘mypassword';
> GRANT ALL PRIVILEGES ON myprojectdb.* TO ‘myusername’@’localhost';
> FLUSH PRIVILEGES;
This assume the user will only connect to this database on localhost.
The Moment of Truth
If everything is set up right, we are ready for our project’s first migration.
We need this because if you look into our project settings.py under INSTALLED_APPS you will find some Django’s builtin apps. Some of them need at least a database table (for example, django.contrib.admin), thus the first migration.
$ python manage.py migrate
The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file.
Back to mariaDB’s command prompt, use SHOW TABLES to show the tables being created
MySQL [(none)]> use myprojectdb;
MySQL [(myprojectdb)]> SHOW TABLES;
You should see information of the previously created table(s) printed to the console. Congratulations! You have connected MariaDB to Django!