Django is a flexible framework for quickly creating Python applications. By default, Django applications are configured to store data into a lightweight SQLite database file. While this works well under some loads, a more traditional DBMS can improve performance in production.
In this guide, we’ll demonstrate how to install and configure MySQL or MariaDB to use with your Django applications. We will install the necessary software, create database credentials for our application, and then start and configure a new Django project to use this backend.
To get started, you will need a clean Ubuntu 14.04 server instance with a non-root user set up. The non-root user must be configured with sudo
privileges. Learn how to set this up by following our initial server setup guide.
When you are ready to continue, read on.
Our first step will be install all of the pieces that we need from the repositories. We will install pip
, the Python package manager, in order to install and manage our Python components. We will also install the database software and the associated libraries required to interact with them.
We will cover both MySQL and MariaDB below, so choose the section associated with the DBMS you’d like to use.
If you want to use MySQL, the following apt
commands will get you the packages you need:
sudo apt-get update
sudo apt-get install python-pip python-dev mysql-server libmysqlclient-dev
You will be asked to select and confirm a password for the administrative MySQL account.
After the installation, you can create the database directory structure by typing:
sudo mysql_install_db
You can then run through a simple security script by running:
sudo mysql_secure_installation
You’ll be asked for the administrative password you set for MySQL during installation. Afterwards, you’ll be asked a series of questions. Besides the first question which asks you to choose another administrative password, select yes for each question.
With the installation and initial database configuration out of the way, we can move on to create our database and database user. Skip ahead to the next section.
If you prefer MariaDB, you can follow the instructions below to install it and perform the necessary initial configuration. Install the packages from the repositories by typing:
sudo apt-get update
sudo apt-get install python-pip python-dev mariadb-server libmariadbclient-dev libssl-dev
You will be asked to select and confirm a password for the administrative MariaDB account.
You can then run through a simple security script by running:
sudo mysql_secure_installation
You’ll be asked for the administrative password you set for MariaDB during installation. Afterwards, you’ll be asked a series of questions. Besides the first question, asking you to choose another administrative password, select yes for each question.
With the installation and initial database configuration out of the way, we can move on to create our database and database user.
The remainder of this guide can be followed as-is regardless of whether you installed MySQL or MariaDB.
We can start by logging into an interactive session with our database software by typing the following (the command is the same regardless of which database software you are using):
mysql -u root -p
You will be prompted for the administrative password you selected during installation. Afterwards, you will be given a prompt.
First, we will create a database for our Django project. Each project should have its own isolated database for security reasons. We will call our database myproject
in this guide, but it’s always better to select something more descriptive. We’ll set the default type for the database to UTF-8, which is what Django expects:
CREATE DATABASE myproject CHARACTER SET UTF8;
Remember to end all commands at an SQL prompt with a semicolon.
Next, we will create a database user which we will use to connect to and interact with the database. Set the password to something strong and secure:
CREATE USER myprojectuser@localhost IDENTIFIED BY 'password';
Now, all we need to do is give our database user access rights to the database we created:
GRANT ALL PRIVILEGES ON myproject.* TO myprojectuser@localhost;
Flush the changes so that they will be available during the current session:
FLUSH PRIVILEGES;
Exit the SQL prompt to get back to your regular shell session:
exit
Now that our database is set up, we can install Django. For better flexibility, we will install Django and all of its dependencies within a Python virtual environment.
You can get the virtualenv
package that allows you to create these environments by typing:
sudo pip install virtualenv
Make a directory to hold your Django project. Move into the directory afterwards:
mkdir ~/myproject
cd ~/myproject
We can create a virtual environment to store our Django project’s Python requirements by typing:
virtualenv myprojectenv
This will install a local copy of Python and pip
into a directory called myprojectenv
within your project directory.
Before we install applications within the virtual environment, we need to activate it. You can do so by typing:
source myprojectenv/bin/activate
Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (myprojectenv)user@host:~/myproject$
.
Once your virtual environment is active, you can install Django with pip
. We will also install the mysqlclient
package that will allow us to use the database we configured:
pip install django mysqlclient
We can now start a Django project within our myproject
directory. This will create a child directory of the same name to hold the code itself, and will create a management script within the current directory. Make sure to add the dot at the end of the command so that this is set up correctly:
django-admin.py startproject myproject .
Now that we have a project, we need to configure it to use the database we created.
Open the main Django project settings file located within the child project directory:
nano ~/myproject/myproject/settings.py
Towards the bottom of the file, you will see a DATABASES
section that looks like this:
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
. . .
This is currently configured to use SQLite as a database. We need to change this so that our MySQL/MariaDB database is used instead.
First, change the engine so that it points to the mysql
backend instead of the sqlite3
backend. For the NAME
, use the name of your database (myproject
in our example). We also need to add login credentials. We need the username, password, and host to connect to. We’ll add and leave blank the port option so that the default is selected:
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
. . .
When you are finished, save and close the file.
Now that the Django settings are configured, we can migrate our data structures to our database and test out the server.
We can begin by creating and applying migrations to our database. Since we don’t have any actual data yet, this will simply set up the initial database structure:
cd ~/myproject
python manage.py makemigrations
python manage.py migrate
After creating the database structure, we can create an administrative account by typing:
python manage.py createsuperuser
You will be asked to select a username, provide an email address, and choose and confirm a password for the account.
Once you have an admin account set up, you can test that your database is performing correctly by starting up the Django development server:
python manage.py runserver 0.0.0.0:8000
In your web browser, visit your server’s domain name or IP address followed by :8000
to reach default Django root page:
http://server_domain_or_IP:8000
You should see the default index page:
Append /admin
to the end of the URL and you should be able to access the login screen to the admin interface:
Enter the username and password you just created using the createsuperuser
command. You will then be taken to the admin interface:
When you’re done investigating, you can stop the development server by hitting CTRL-C in your terminal window.
By accessing the admin interface, we have confirmed that our database has stored our user account information and that it can be appropriately accessed.
In this guide, we’ve demonstrated how to install and configure MySQL or MariaDB as the backend database for a Django project. While SQLite can easily handle the load during development and light production use, most projects benefit from implementing a more full-featured DBMS.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Great tutorial. Thank you very much.
Is the ‘libmariadbclient-dev’ package available by default in Ubuntu 15.04?
Judging by content on stackoverflow, I’d say that, yes, ‘libmariadbclient-dev’ is in the Ubuntu repos.
Very well-written tutorial for general use of django and mariadb on Linux. Works with DigitalOcean, as always! :D
What about the web server? Or should we stick with the development web server?
Not working for me, mi problem is specific, I tried create a database with timestamp fields with auto now add setted to True, so when I retrieve information about this column the time stamp is without microseconds precision, I research infromation about that, I found in django/db/backends/mysql/features.py a method named supports_microsecond_precision that returns self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5), when you use MariaDB, supports_microsecond_precision always return False, because the current version in MariaDB is 5.5, so django creates a table without microseconds precision. You can see that in django/db/backend/mysql/base.py in data_types method, I tried create a custom database backend too, without success, because django has a internal validation in django/db/utils.py that ensures the ENGINE is in db/backends/ directory.
I conclude that the MySQL driver for django is not 100% compatibility with MariaDB
Hi,
Just read this guide, please update the character set to
utf8mb4
for full unicode support, utf8 is not the complete standard.Read more on the mysql website.
Thanks
Thanks for this great article Justin.
I am really confused for the following things. Maybe what I am asking is silly but clarifying these things is better than being actually silly -
Thank you.
@sgauri61 Hey there. Let me see if I can clarify a little bit.
Question 1: Let’s start off with 0.0.0.0:8000 vs 127.0.0.1:8000.
By default, the Django development server serves the app on the address
127.0.0.1
and port 8000, as you say. The127.0.0.1
address is the local loopback device. It basically means that it will make the application available to clients located on the same machine. So if your web browser is on the same computer as your Django development environment, binding to that address allows you to access your application from that machine (no other computer will be able to connect to your application, which is good for development).However, if your web browser is on a different machine than your Django installation (as in this guide, where we are setting up Django on a remote server), the
127.0.0.1
address won’t work (the browser would try to find your application on its own computer). Instead, we bind to the address0.0.0.0
, which is actually a catch-all address that means “make this application available on every address that this machine owns”. So we start up Django with0.0.0.0
to mean that it should respond to requests on its public interfaces too, which is what we have to use to access the application from a different computer.While
0.0.0.0
means “every available interface” when you’re starting up an application or server, it shouldn’t be used to access the application. To access it, you should use the Django installation’s public IP address.Question 2: The error you’re receiving about disallowed hosts is actually caused because newer versions of Django require you to set the
ALLOWED_HOSTS
setting in the~/myproject/myproject/settings.py
file. When this guide was originally written in 2015, this wasn’t a requirement, so this guide is a bit out of date.You can open that file in a text editor and search for the
ALLOWED_HOSTS
directive. Inside, you will want to define any IP address or domain that you may wish to use to access your site. This would include your server’s domain name if it has one, it’s public IP address, etc. This is a safety mechanism that Django introduced to help prevent a certain type of security vulnerability. You can find a bit more information in this guide, which was written a bit more recently (it should be applicable even though it’s about a slightly different topic). Search forALLOWED_HOSTS
to get a description of the way to fill out that option.Question 3: We can leave the
PORT
specification blank because we’re running MySQL on the default port. If there is no port defined, Django will try to connect using MySQL’s default port (3306), which is exactly what we want.Hope that helps to clarify! Good luck!
@jellingwood Hey, that was great insight. Thank you very much.
I said: VERY HELPFULL friend!!!
thanks a lot, you are so great!!!