How to Connect Django to MySQL: A Complete Step‑by‑Step Guide

This tutorial walks through configuring a Django project to use MySQL instead of the default SQLite, covering database creation, settings adjustments, required package installation, migrations, and a complete example with URLs, views, templates, and server startup.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Connect Django to MySQL: A Complete Step‑by‑Step Guide

Introduction

This article briefly explains how to connect Django to MySQL.

By default Django uses SQLite, which is convenient for quick testing but can cause obscure issues in production, so configuring MySQL early is recommended.

Connecting to MySQL

Django connects to MySQL in three steps:

Create the MySQL database in advance.

Modify settings.py to use the MySQL engine.

Update the project’s __init__.py to use pymysql as MySQLdb.

1. Create MySQL database

Example: a database named school on the local MySQL server.

2. Edit settings.py

Replace the default SQLite configuration with the following:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # default
        'NAME': 'school',                      # database name
        'HOST': '127.0.0.1',                   # MySQL IP
        'PORT': 3306,                          # MySQL port
        'USER': 'root',                        # username
        'PASSWORD': 'rootroot'                 # password
    }
}

3. Edit __init__.py

Install pymysql if not present and add:

import pymysql
pymysql.install_as_MySQLdb()

Install with pip install pymysql if needed.

Migrate Database

After configuration, create a demo app to test:

Create an app: python manage.py startapp web Add the app to INSTALLED_APPS in settings.py.

Run migrations: python manage.py makemigrations and python manage.py migrate.

Display Content

The demo consists of four parts:

Define URLs in urls.py.

Write the view in web/views.py.

Create the template templates/student.html.

Start the server with python manage.py runserver 127.0.0.1:8000 and visit http://127.0.0.1:8000/student_list.

URL configuration example:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('student_list', views.student_list),
]

View example:

def student_list(request):
    student_queryset = models.Student.objects.all()
    return render(request, "student.html", {"student_queryset": student_queryset})

Template example (simplified):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student List</title>
</head>
<body>
<table border="1">
    <thead>
        <tr><td>id</td><td>姓名</td><td>年龄</td><td>性别</td><td>年纪</td></tr>
    </thead>
    <tbody>
        {% for student in student_queryset %}
        <tr>
            <td>{{ student.id }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.gender }}</td>
            <td>{{ student.grade }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

Run server command:

python manage.py runserver 127.0.0.1:8000

Visit http://127.0.0.1:8000/student_list to see the rendered table.

Conclusion

The article demonstrates how to connect Django to MySQL and provides a small demo showing the full workflow from configuration to a running web page. It notes that pymysql version 0.9.2 and Django 2.1.5 were used.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonBackend DevelopmentMySQLDjangodatabase-connectionWeb Tutorial
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.