Official Power Up Hosting Blog

Everything about Linux, Windows, and hosting ;)

Selvakumar
Author

I am an Online Marketer and technology lover. I like to learn new things and share that with people.

Share


Our Newsletter


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Tags


Twitter


Official Power Up Hosting Blog

(6 Steps Django Database Tutorial) Create App and Connect a Database

SelvakumarSelvakumar

Django is the Python Framework which provides the Scalability and Rapid development environment.

You don't need to bother about development and Django allows the reusability.

You can enjoy the hassle-free and rapid development with Django.

Here:

The Django tutorial for beginners will teach you the following.

You are going to learn How to create a blog foundation and create MySQL and connect both of them.

You will be creating a skeleton structure of the web application. For that, you will use the django-admin.

Then, you will be creating a MySQL database. After that, you have to connect the web application to that database.

Prerequisites

  • You should have installed the Django on your Ubuntu 16.04 server. Also, the server has to be configured according to the Ubuntu initial server setup guide.

  • You should have MySQL installed on Your Ubuntu 16.04 server. If you have not installed the server yet, just follow this tutorial to install the latest version of MySQL.

The above setup is required for this Django Python tutorial.

Once the above setup was done, then we can start creating the application.

Django Project Skeleton Creation

To initiate the work of the django example web application, you have to Create a Project Skeleton.

The project skeleton will be the foundation of our application. We will be doing this by using the django-admin command.

Switch to the Home directory using the cd command.

$ cd ~

If you want to see the current content of the directory, use the ls command to list those directories.

$ ls

If there is any folder already exist, it will be displayed in the output.

Here:

We will create a new directory. You can name the directory based on your choice.

But:

The name should be understandable. Here, we will name the directory as blog_application.

Use the below command to create the directory.

$ mkdir blog_application

Once created, move to the new folder.

$ cd blog_application

Now:

Let us generate the project using the Django create app command.

$ django-admin startproject blog

The project now should create a directory called blog. You can check that by navigating to the /blog directory.

$ cd blog

The directory structure will be like this /blog_application/blog.

After executing the django admin command, the blog folder will be created inside the /blog_application folder.

Now:

You have to check the whether the required items were created. For that use the ls command to list all the items inside the directory.

$ ls

You will get the following output.

  Output
blog manage.py

Here:

You have created the Project directory with the required things for the initial development.

We will move onto the next step.

Configure the Settings

We have created the Skeleton Project. In that, we will be having the settings.py file.

Since the blog has to be in our current time, we will be editing the settings.py file.

Here, We will use our local time, America/Los_Angeles in the settings.

If you want to set any other time, just refer this global time here.

The settings.py file is located at ~/my_blog_app/blog/blog/.

We will move to that directory using the cd command.

$ cd ~/my_blog_app/blog/blog/

Now, Open the settings.py file using the file editor. Here I am using the nano editor.

$ nano settings.py

The file will open. In that, you have to make changes in the TIME_ZONE field.

Scroll down to the bottom section. You can see the TIME_ZONE field.

settings.py
...
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
...

Here, I am going to make changes in the TIME_ZONE field and I am going to set the Los Angeles time.

             settings.py
...
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Los_Angeles'

USE_I18N = True
...

The process is not yet over. You have to add the path to the static file.

The file served from the Django web application called static file. It can be the CSS, Javascript and images.

Go to the bottom of the file and find the section that looks like below and makes changes as mentioned below.

settings.py
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

You have added the Time Zone and path of the static file. The next task is to add our IP to the Allowed Host field.

Search and find the section of the file which contains the ALLOWED_HOSTS.

settings.py
...
# SECURITY WARNING: don't run with debug turned on in 
production!
DEBUG = True

ALLOWED_HOSTS = ['IP address']

# Application definition
...

Add your IP address instead of the text.

Now:

It is the time to save the changes that you have made on the settings.py file.

In this settings.py file, you have configured the Time Zone, Static file path and then Hosted IP Address for the application.

The next task is to setup the database connection.

MySQL Database connecter Installation

We have to connect the database to the application. To do that we need a python 3 database connector which should be library compatible with the Django.

So, we have to install the database connector, mysqlclient.

The mysqlclient is the forked version of MySQLdb.

The mysqlclient document says mysqlclient is the interface with thread compatibility to MySQL server which provides the Python database API.

The mysqlclient provides the support for the Python 3.

You have to install the python3-dev. To install the python3-dev, use the below command.

$ sudo apt-get install python3-dev

After that, install the MySQL and Python headers and libraries.

$ sudo apt-get install python3-dev libmysqlclient-dev

You will get the following output.

Output
After this operation, 11.9 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

Press y and then press enter.

To install mysqlclient library from Pypi, we have to use the pip3.

Here is the command for that.

$ sudo pip3 install mysqlclient

You will get the following output.

successfully installed mysqlclient
Collecting mysqlclient
Downloading mysqlclient-1.3.10.tar.gz (82kB)
100% |████████████████████████████████| 92kB 6.7MB/s
Building wheels for collected packages: mysqlclient
Running setup.py bdist_wheel for mysqlclient ... done
Stored in directory: /root/.cache/pip/wheels/32/50/86/c7be3383279812efb2378c7b393567569a8ab1307c75d40c5a
Successfully built mysqlclient
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.10

If you get the above output, then the mysqlclient is installed on your server.

Database creation

You have to configure the Django backend for the MySQL compatibility.

To do that, first, initiate the MySQL service using the below command.

$ systemctl status mysql.service

You will get the following output.

starting mysql.service
mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2017-08-19 11:59:33 UTC; 1min 44s ago
 Main PID: 26525 (mysqld)
 CGroup: /system.slice/mysql.service
    └─26525 /usr/sbin/mysqld

After that, log into the MySQL using the following commands.

$ mysql -u db_user -p

Here, the -u refers the username and -p refers the password.

You will be prompted to enter the password.

After entering the password, you will get the following output.

Output
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.19-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

To view the available database, use the below command.

mysql> SHOW DATABASES;

Since you have not created any database yet, you will get the following output.

Output
+--------------------+
| Database          |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
4 rows in set (0.00 sec)

You can see the default database.

information_schema, mysql, performance_schema and sys are the four databases.

We are not going to touch these databases as they contain the information required by the MySQL server.

So, we have to create a database to store the data of the blog.

To create a database, use the below command. Using this command we will create a database name "blog_data".

mysql> CREATE DATABASE blog_data;

If the database is created successfully, you will get the following output.

Output
Query OK, 1 row affected (0.00 sec)

There is a chance that you may get two types of errors. Let us see them here.

Error 1:

database creation failed
ERROR 1007 (HY000): Can't create database blog_data; 
database exists

If you get the above output, then it means that a database is existing already with the name 'blog_data'.

Error 2:

If you get the below error, then it means that you have made an error in the syntax. Most of the time, people forgot to add the ':' at the end of the each command.

database creation failed
ERROR 1064 (42000): You have an error in your SQL syntax;

Now:

You have to verify that the database which you have created has been listed.

Use the below command for that.

$ SHOW DATABASES;

Now, you should see the blog_data database in the list.

output
+--------------------+
| Database          |
+--------------------+
| information_schema |
| blog_data         |
| MySQL             |
| performance_schema |
| sys               |
+--------------------+
5 rows in set (0.00 sec)

A database has been created for your application to use. If you want to exit from the MySQL using CTRL+D.

Add the MySQL Database Credentials to the Application.

We have to add the database credentials to the Django Application.

Here is how the connection settings will look like.

- OPTIONS
- NAME, USER, PASSWORD, HOST, PORT
- MySQL option files.

Now:

Go to the settings.py file and then replace the database lines with the following line.

Once you configure, the Django will start using the MySQL as the Backend. It will also read and write data in the Database.

settings.py
...
# Database
# 
#  

https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'OPTIONS': {
        'read_default_file': '/etc/mysql/my.cnf',
    },
}
}
...

After that, you have to edit the configuration file. Open the configuration file with the nano editor.

$ sudo nano /etc/mysql/my.cnf

my.cnf
...
[client]
database = db_name
user = db_user
password = db_password
default-character-set = utf8

Here, the database name is blog_data. If you set any other name, make sure to use that name here.

Fill the username and password for the MySQL. Here, the utf8 encoding will be used to encode the MySQL data in the Unicode.

Now, restart the MySQL to make the changes to take effect.

$ systemctl daemon-reload
$ systemctl restart mysql

The next step is to check the MySQL connection to the database.

Checking the MySQL connection to the Application

Here, we have to check whether credential and connection to the server is working properly.

To check that, start running the server. If the server is running, then it means the connection to the database is working properly.

If the server is not running properly, then you have to check the connection settings.

First, switch to the following directory.

$ cd ~/my_blog_app/blog/

After that, execute the following command.

$ python3 manage.py runserver your-server-ip:8000

You will get the following output.

Output
Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 19, 2017 - 15:45:39
Django version 1.11.4, using settings 'blog.settings'
Starting development server at http://your-server-ip:8000/
Quit the server with CONTROL-C.

After that, go to the following URL. http://your-server-ip:8000/.

The page should display a message. "It Worked!

Congratulations on your first Django-Powered Page.

Conclusion

You have learned How to Create a Django App and connect it to the Database.

You also learned MySQL and Django configuration.

If you have any doubt or facing the issues in executing the article, Leave your query in the comment section.

We will help you to solve your issue.

Also, don't forget to signup for the Upcoming tutorials.

Selvakumar
Author

Selvakumar

I am an Online Marketer and technology lover. I like to learn new things and share that with people.

Comments