Skip to main content

How to connect django project with Mysql database




This article will guide you through the set up process of the Django project  with connections to a MySQL database.So that app's installed on this project they can use MySQL database instead of the default sqlite3 database.

Prerequisites: 

You must have python installed within you environment,  MySQL must be installed and running
With the prerequisites taken care off and our Django development environment set up, we can move on to integration/inner-workings.

Step 1

You will need to navigate to where you want your django project to live

cd  django
mkdir django_projects
cd django_projects
python3 -m venv venv     # create Python virtual environment
source venv/bin/activate  #  activate your Python virtual environment
pip3 install Django #  install Django within the virtual environment
django-admin startproject news_art # creates the project
Note: Since Django creates extra directory I usually like to clean things up a bit, this is not necessary but for simplicity and clarity I will move things around one level down, and delete that extra directory created by django.  
mv news_art/manage.py ./
mv news_art/news_art/* news_art/
rm -r news_art/news_art/
Now that you’ve created a project directory  we can continue on to the next step.

Step2-Edit settings.py

We will need to add some basic settings on the settings.py file of our project 
including adding all network adapters instead of the default behavior of listening to the local host adapter as well as  replacing the default database sqlite3 to MySQL, adding time zone  of your specific area and final we will add a path for our static files. 
NOTE: adding time zone and configure the path for static files have nothing to do with MySQL setup this is for the feature usage only. And I find it to be best practice when setting up your project.  
 
nano news_art/settings.py
ALLOWED_HOSTS = ['*'] # on line 28: add this  ['*']

DATABASES = { # line 76 replace the existing code with this
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {'read_default_file': '/etc/mysql/my.cnf',
    },
  }
}

TIME_ZONE = 'Africa/Dar_es_Salaam' # line 115 replace it with your Time zone

STATIC_ROOT= os.path.join(BASE_DIR, 'static') # line 127 add this
STATICFILES_DIRS = [                                          # line 128 add this, make sure in your project dir
        os.path.join(BASE_DIR, 'news_art/static'.......  you create this directory static
]



Step 3 — Install MySQL Database Connector

I assume you already have MySQL server installed. In order to use MySQL with our project, we will need a Python 3 database connector library compatible with Django. So, we will install the database connector, mysqlclient, which is a forked version of MySQLdb.Since we are using Python 3 it makes sense to use mysqlclient hence it support  Python 3



apt install default-libmysqlclient-dev # MySQL development headers and libraries:
pip3 install mysqlclient #Then, we will use pip3 to install the mysqlclient library from PyPi

Step 4 — Create the Database

Now that mysqlclient,mysql-server
have been installed, we will  need to configure your Django backend for MySQL compatibility.
mysql -u root -p
CREATE DATABASE localblog;
GRANT ALL PRIVILEGES ON *.* TO 'localblog'@'%' IDENTIFIED BY 'localblog' WITH GRANT OPTION;
FLUSH PRIVILEGES;

exit;


Step 5 — Add the MySQL Database Connection to your Application

Finally, we will be adding the database connection credentials to your Django project

nano /etc/mysql/my.cnf  # at the end of the file add this

[client]
database = localblog
user = localblog
password = localblog
default-character-set = utf8

systemctl daemon-reload # we need to restart MySQ ... 
systemctl restart mysql # for the changes to take effect
                                                   # Note that restarting MySQL takes a few seconds, so be patient.



Step 6 — Test MySQL Django Connection 

Final we need to verify that the configurations in Django detect your MySQL server properly. We can verify this simply by running the server. If it fails, it means that the connection isn’t working properly. Otherwise, the connection is valid.

python3 manage.py runserver 192.168.1.245:8000 # run the server
 Watching for file changes with StatReloader         # you will get out put like this
Performing system checks...

System check identified no issues (0 silenced).

You have 17 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.


May 11, 2019 - 14:59:00
Django version 2.2.1, using settings 'news_art.settings'
Starting development server at http://192.168.1.245:8000/
Quit the server with CONTROL-C.


 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 project. Please continue and follow the suggested link from the output in my case http://192.168.1.245:8000/

Popular posts from this blog

django react app setting up the backend

On the previous article I demonstrated how we can use the generic views along with ModelSerializer classes to rapidly develop our REST APIs. Knowledge that you will need  in your career as full stack / backend developer, however think of this article as an extension to the previous one, equipped with what we already know about REST API we will step our game up and discuss about ViewSet, ModelViewset we will dig deep into the concepts of Routers which allow us to manage our api routes in a simple and sophisticated manner as well as helping to speed up building APIs even further. There for on part II of this article i'll work you through on how React application can consume this RESTful API. There for at the end of the day we will have a full stack web app, in short we strat our development at the backend then later on we move at the frontend... so are you excited and ready to take the challange? lets do this then..... you can get source code for the bakend on github Preparat...

How to Install PostgreSQL on debian stretch in oder to use it with your Django application and allow remote connection

In this guide, we'll demonstrate how to install and configure PostgreSQL to use with your Django applications. We will install the necessary software, create database credentials for our application, and then start and configure a Django project to use this backend. We will start by  install the database software and the associated libraries required to interact with them. This guide assumes that you allready have a working Django project. Step 1 – Prerequsities apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib Step 2 – Connect to PostgreSQL After installing the PostgreSQL database server by default, it creates a user ‘postgres’ with role ‘postgres’. It also creates a system account with the same name ‘postgres’. So to connect to postgres server, login to your system as user postgres and connect database. su - postgres You should now be in a shell session for the postgres user. Log into a Postgres session by typing:...

How to create REST API using Django REST Framework

This post begins with already working project and app's, I found that there some few requirement's that my project needed to handle and the best option for those requirement's was to use the Django's  Rest Framework. The way that I will tackle this task is more specific to the needs of the project rather than a one to one how to..., that being said you can still follow along, the approach that I'm going to use is easy to follow since I'll be providing a lot of information a log the way for better understanding of the why and how.....this code is available on Github , enough with the alerts and on with the show. Note:  If you would want to mimic the exactly settings then you will need to enable user authentication on your project you can follow this link for details .  Start with the DRF (Django Rest Framework) installation pip3 install djangorestframework For our app to use DRF, we'll have to add rest_framework into our settings.py.   nan...