Installation and Setup of Django with MySQL in Ubuntu 18.04 Walkthrough

Installation and Setup of Django with MySQL in Ubuntu 18.04 Walkthrough

14/04/19   15 minutes read     1261 Naren Allam

In this article, we cover the topics Django Installation, Django Application Creation, MySQL Installation, MySQL Setup on Django by which we can build Django web applications .


Prerequisites


  We will need a computer with Ubuntu 18.04 installed, as well as have administrative access to that machine and an internet connection.

Django Installation


  Django Software Foundation recommends to use Python3 for development of Django web applications. Python3 comes by default with Ubuntu 18.04 installation. So, we don't need to install it separately.

To check the python version, run the command

BASH  Copy
                    
                      $ python3 --version     # Or use 'python3 -V'


                    
                  

In order to install Django with pip, we need to install 'python3-pip' package to the ubuntu 18.04 system.


What is pip?

  Pip is a package management system for python. Python has a central package repository from which we can download the python package. It's called Python Package Index (PyPI).

For installing it, we must first update the local APT repository. So, run the following commands

BASH  Copy
                    
                      $ sudo apt-get update && sudo apt-get install python3-pip
                    
                  

Now that we have pip installed, that means we have the ability to quickly install other necessary packages for a Python environment.

But before installing Django, we also have to install virtualenv.


What is virtualvenv?

  The virtualenv package allows us to create virtual environments where we can install software and Python packages in a contained development space, which isolates the installed software and packages from the rest of our machine’s global environment. This convenient isolation prevents conflicting packages or software from interacting with each other. By using this method, we can install Django without affecting the entire system.

First create a directory and navigate into it by running the following

BASH  Copy
                    
                      $ mkdir django && cd django


                    
                  

Now install 'virtualenv' by running the command

BASH  Copy
                    
                      $ sudo apt-get install virtualenv
                    
                  

Now create a virtual environment with any name (for example, 'venv') using the virtualenv package installed, and also activate the environment by running the command

BASH  Copy
                    
                      $ virtualenv -p python3 venv && source venv/bin/activate
                    
                  

We will know that we have virtualenv started, when we see that the prompt in our console is prefixed with (venv).

Note:- To come out of the environment, type the command 'deactivate' and press 'Enter' button on the keyboard.

When working within a virtual environment, python will automatically refer to the correct version so we can use python instead of python3.

Now we need to install various development libraries required to build the application. They includes python3-dev for compiling any Python extensions and their supporting standard libraries, as well as the libmysqlclient-dev package, which is required to build the MySQL client in the todo backend application.

This can be done by running the below commands in the terminal

BASH  Copy
                    
                      (venv) $ sudo apt-get install python3-dev 
(venv) $ sudo apt-get install libmysqlclient-dev
                    
                  

Now we have all important dependencies in place. So, we can finally install Django and all the other tools required to develop django web application.

To install them, run the command

BASH  Copy
                    
                      (venv)$ pip install django pillow djangorestframework
                    
                  

Here we have installed django, pillow and djangorestframework.


What is Pillow?

  Pillow is a Python Image Library.This provides image validation (as well as many other image-related python activities) for Django's ImageField(). The Python Imaging Library adds image processing capabilities to your Python interpreter. This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. For non-image file uploads, pillow is not needed.

What is django rest framework?

  Django REST framework is a powerful and flexible toolkit for building Web APIs. REST framework requires Python (3.5/3.6/3.7) and Django (1.11/2.0/2.1/2.2).

After successful installation check whether they were installed or not by running the command

BASH  Copy
                    
                      (venv)$ pip freeze
                    
                  

Thus we have installed Django and other tools which are needed to get started building Django web applications.

So, we can start creating our first django project.

Django Application Creation


As the installation and setup is completed successfully, we will create our first django project named 'project' and navigate into the project directory by running this command

BASH  Copy
                    
                      (venv) $ django-admin.py startproject project 


                    
                  

In the above command, django-admin tool creates the project folder, basic file templates and project management script (manage.py).

Now navigate into 'project' folder and then we can look to see what project files were just created by running the command 'ls' to list the contents of that directory (to see what files were created).

BASH  Copy
                    
                      (venv) $ cd project
(venv)$ ls
                    
                  

We will notice the output that shows this directory contains a file named manage.py and a folder named project.

The manage.py file is similar to django-admin and puts the project’s package on sys.path. This also sets the DJANGO_SETTINGS_MODULE environment variable to point to our project’s settings.py file.

The manage.py script is used to create applications, work with databases, and start the development web server. It’s a convenience script that allows you to run administrative tasks like runserver , createsuperuser , migrations of your database models.

We can view the manage.py script in our terminal by running the 'less' command like so

BASH  Copy
                    
                      (venv)$ less manage.py
                    
                  

When we’re finished reading the script, press 'q' to quit viewing the file.

Now navigate to the 'project' directory to view the other files that were created. To list the contents of the directory, run 'ls' command

BASH  Copy
                    
                      (venv)$ cd project
(venv)$ ls
                    
                  

We will see four files like this :


Here we will look into the files generated automatically, why they are created , what are the purposes that they will solve for our project.

  • __init__.py —  This file acts as the entry point for our Python project.

  • settings.py —  This file describes the configuration of our Django installation and lets Django know which settings are available.

  • urls.py —  This file contains a urlpatterns list, that routes and maps URLs to their views.

  • wsgi.py —  This file contains the configuration for the Web Server Gateway Interface. The Web Server Gateway Interface (WSGI) is the Python platform standard for the deployment of web servers and applications.


Now we have to edit the 'settings.py' using favorite code editor (I prefer visual studio code editor).

If visual studio code is not installed in the machine, we have to install it first.

Visual Studio Code is available as a Snap package. Snaps are special kind of packages that are usually big in size. So it will take some time in downloading and installing the Snap package depending upon our internet speed.

To install it, run the command

BASH  Copy
                    
                      (venv) $ sudo snap install code --classic
                    
                  

After installation, to open the project directory in visual studio code editor, run the command

BASH  Copy
                    
                      (venv)$ code .
                    
                  

Now create an application named 'app' for this project. To create app, make sure we’re in the same directory as manage.py and run the command

BASH  Copy
                    
                      (venv) $ cd ..
(venv) $ django-admin.py startapp app
                    
                  

That’ll create a directory named 'app'. Now navigate to 'app' directory and here we can look to see what app files were just created by running the command 'ls' to list the contents of that directory (to see what files were created). We will notice the output that shows like this


Let’s dive into the files automated generated for the django applications. Since Django framework wants you to work professionally and maintain your applications in such a way that anyone looking to your code can easily understand your hard work.
  • admin.py —  This file is used for registering your django models to the Django Administration. We will be using django-import-export package for importing and exporting the data through Django Administration.

  • apps.py  — This file is created to help the user include any application configuration for the app. Using this, you can configure some of the attributes of the application. But I do not have any personal experience in configuring this file as most of the times Default Configuration is sufficient for our Project.

  • models.py — This file is used to write Class based Models for our Django Applications.This will be the blueprint of our database design, relationships and attribute constraints.

  • tests.py — This file is used to write test cases for the Application. For time being we will not go into the details of this. As I personally found this little bit complex to understand. We will be writing out separate tutorial for this.

  • views.py  — This file will be most crucial one , we will be defining our Class Based List Views , CustomFilter Views and Detail Views for our Django Models through Serializers using Django Rest Framework. These are the classes which will be actually handling the HTTP Requests.


Now add the created 'app' to INSTALLED_APPS in settings.pyfile of project folder using Visual studio code as shown below.

Remove the default database engine that is automatically set for you.

By default, Django adds the SQLite3, we don’t want that. So, remove the definitions from DATABASES in settings.py. It should look like this, after you remove the default key:

PYTHON  Copy
                    
                      DATABASES = {
}
                    
                  

Here, we need to verify that the application is working properly or not. We can do this by simply running the server. To run the server, use the command

BASH  Copy
                    
                      (venv) $ cd ..
(venv) $ python manage.py runserver
                    
                  

The command will run django server on port '8000' as shown below

Note:- You will see that you have unapplied migrations in the output. But, don’t worry, this does not affect the initial setup of our application.

So, open the web browser and go to http://localhost:8000/ to check if you see a Welcome page like this

Note 1:- Press 'Ctrl+c' to exit from the django runserver.

With the project and app created, we now need to sync our database for the first time and also create an initial user(superuser/admin) and set a password for that user. Before this we need to install MySQL as we decided to use in our project.

MySQL Installation


In order to use MySQL with our project, we must install MySQL server. To do so, first deactivate the environment and install mysql-server as shown below.

BASH  Copy
                    
                      (venv) $ deactivate   
$ sudo apt-get install mysql-server 
                    
                  

After successful installation, connect to MySQL server by running the below command.

BASH  Copy
                    
                      $ sudo mysql
                    
                  

Now we have to set password for the 'root' user of MySQL. This can done by running the following command

SQL  Copy
                    
                      > ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mypassword';
                    
                  

The above command tells MySQL to change the password for 'root' user at 'localhost'.

As a final step following any updates to the user privileges, be sure to save the changes by issuing the FLUSH PRIVILEGES command from the MySQL prompt This tells database server to reload the grant tables

Then to come out of the shell use EXIT command.

SQL  Copy
                    
                      > FLUSH PRIVILEGES;
> EXIT;
                    
                  

As we set the password for the 'root' user, now login as root user by the command given below.

Note: When you input the password, it will not be visible.

BASH  Copy
                    
                      $ mysql -u root -p 
password: ***********

                    
                  

Now create a new user by issuing the command

SQL  Copy
                    
                      > CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

                    
                  

Now we have to grant all privileges to the 'user' with 'grant option'. This can be done by running the command

SQL  Copy
                    
                      > GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' WITH GRANT OPTION;

                    
                  

With GRANT OPTION user can grant other users, permissions to the database.

To come out of the MySQL shell, type the command

SQL  Copy
                    
                      > exit;
                    
                  

Then login as user for checking, whether the user is created or not.

Note: When you input the password, it will not be visible.

BASH  Copy
                    
                      $ mysql -u username -p
Password: ***********
                    
                  

After login, create any database named 'webnews' for our project which we will you later. To create a database in MySQL, run the command

SQL  Copy
                    
                      > create database webnews;
                    
                  

To check whether the database is created or not, run the command

SQL  Copy
                    
                      > show databases;
                    
                  

Then come out of the MySQL Shell by running the EXIT command.

SQL  Copy
                    
                      > exit;
                    
                  

MySQL Setup on Django


Now we need to install mysqlclient in the virtual environment. To install it, run the commands

BASH  Copy
                    
                       # activate the virtual environment
$ source venv/bin/activate

# install mysqlclient
(venv) $ pip install mysqlclient
                    
                  

Add the MySQL database connection settings like db_name, username, password etc.., in settings.py file.

Our configuration should look like as shown below

Then save the changes made by pressing 'Ctrl+s'.

Next, we have to configure the Django admin. Django will automatically generate the database for a superuser. Before we create the superuser, create a set of rules by running the command

BASH  Copy
                    
                      (venv) $ python manage.py makemigrations
                    
                  

'makemigrations' generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py).

It does not execute those commands and so tables will not be created after makemigrations.

After applying makemigrations we can see those SQL commands with sqlmigrate which shows all the SQL commands which has been generated by makemigrations.

Now to apply all the migrations, run the command

BASH  Copy
                    
                      (venv) $ python manage.py migrate
                    
                  

'migrate' create the table in SQL database using the commands which have been generated by makemigrations.

The migrate command looks at the INSTALLED_APPSsetting of project/settings.py file and creates any necessary database tables according to the database settings in the project/settings.py file.

We’ll see a message for each migration it applies as shown below.

Django automatically creates 10 default tables in MySQL database. To verify this login to mysql database and check as shown below.