Connect MySQl(PhpMyAdmin) with Django

Vinoth Saravanan
3 min readApr 24, 2021

By default, Django provides database access to sqlite3. Here we are going to connect Mysql database with Django.

Prerequisites :
1. XAMPP Server
We need to install XAMPP server to handle this process.
https://www.apachefriends.org/index.html we can download the XAMPP server using this link.

After installing XAMPP server, UI will be look like this. We need to start Apache and MySQL by clicking the start button under action. The server will be on for the whole process. If we stop the server then we can’t access the database in our application.

In browser open 127.0.0.1. It will explore the phpmyadmin home page. Now we need to click the phpMyAdmin button on the right corner of the page.

After opening the phpMyAdmin page, we can see the db look alike web page. In the left panel, we can find list of db’s. We need to create new db by clicking the New in left panel.

Enter the database name(any name) and click create. In this example, I’m giving ‘dbtaskapp’.

After creating db successfully, we are moving to Django code part. I’m using windows 10 operating system and for VS code editor. In two ways we can create the tables in db. One way is creating in phpMyAdmin page and another way is, creating models and migrating in Django application. We go for the second option.

Create a project and app using django-admin.

We need to install two packages.
pip install mysql_connector
pip install mysql

We need to update the database settings in settings.py. Here Name is the database name which we created earlier in phpMyAdmin. Other details are default values.

Database settings in settings.py

In models.py file, write the below code. Three fields will be create in the table named as ‘dbuser’. After updating models.py run
python manage.py makemigrations
python manage.py migrate.
This will create a table in phpMyAdmin page. we can check it in that page.

models.py

Create a html form like below with method = ‘POST’. Give the name for input fields as we created in models.py.

main.html
output of html form

We need to grab the html input data in views and send it to database. Import models in views.py by from .models import *’. Referring userdb model in a variable called table. table.save() will save the html input into database table.

views.py

Yes, That’s it. After submitting the form everytime, new record will be create in the table. We can check via phpMyAdmin web page. Please comment, If there is any query regarding this.

--

--