How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect with Django like SQLite, PostgreSQL, MySQL, MariaDB, Oracle. In this tutorial, we will learn how to connect Django with MySQL.

Django supports MySQL 5.7 and higher versions. The database should support Unicode (UTF-8 encoding) and delegate it to referential integrity and enforcing transactions. MySQL does not enforce referential integrity and transactions when the MyISAM storage engine is used. MySQL's default storage engine, InnoDB, is fully transactional and supports referential integrity.

STEP 1: Install MySQL

Install MySQL 5.7 or higher version on your machine.

STEP 2: Create A Django Project

  • Navigate to the directory you want to create the project and run the following command in the CMD:
>django-admin startproject <project_name>
  • Navigate to the project directory
>cd <project_name>
  • Now go to the directory where the project is created, and you must see a folder with the project_name and a file called manage.py
  • After you find the file manage.py start the server by running the following command:
>python manage.py runserver

Make sure that you are in the project directory. After running the above command, you might see the following output in the cmd.

How to Connect Django With Mysql
  • When the server is started, go to the project directory you will see a file called “db.sqlite3" as the default database configured is SQLite.

Step 3: Install MySQL Connector

We need to install a database connector library in order to use MySQL with the Django project. The following command is used to install the mysql-connector-python library, which does not require any client library or additional adapter to access the database from ORM outside the standard module as it has its own.

> pip install mysql-connector-python

Step 4: Create Database

Create a database in MYSQL with InnoDB as a storage engine.

Step 5: Configuring the Database Connection in The Settings.Py

  • The database connection details and the project settings are stored in the file called settings.py, which is created by default when the project is created. When the app is created, and the server is started, a file named "db.sqlite3" is created in the project directory because the default setting has SQLite Database configured. Other databases can be configured manually by making changes in the predefined dictionary is called DATABASES in the settings.py file.
  • The connection details are provided in the settings.py file.
  • Several other connection details are required for the database connectivity, such as:
    • ENGINE: The backend database to be used
    • OPTIONS: The path to the options files that contains commonly used options. If the database name is specified in OPTIONS, it takes precedence over NAME
    • NAME: Database Name
    • USER
    • PASSWORD
    • HOST
    • PORT
  • mysql.connector.Django is the driver that is used to establish a connection between the application and the SQL database. It is possible to add more connection arguments using OPTIONS.

settings.py

DATABASES = {
'default': {
'ENGINE': 'mysql.connector.django',
'NAME': 'djangoApp', 
'USER':'root', 
'PASSWORD':'mysql',  
'HOST':'localhost', 
'PORT':'3306'
'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

my.cnf

[client]
database = database_name
user = django_user
password = actual_password
default-character-set = utf8

Step 6: Migration

After all the changes, migrate all the Django tables to MySQL schema.

>python manage.py migrate

Make sure you are present in the project directory.

Conclusion

These simple steps allow us to connect MySQL with Django.


Related Topics

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.