Django MySQL: Configure a Database and Create Tables

Recommended preparation: set up a Django project and read the Django tutorial overview before trying the code.

Django connects to MySQL through its database backend and a supported driver such as mysqlclient. Define a model in Python, generate migrations and apply them rather than manually creating the main table.

Install Django 5.2 LTS and the MySQL database driver

# Run in an activated virtual environment
python -m pip install "Django>=5.2,<5.3" mysqlclient

You need a running MySQL server, an existing database and a database user with suitable permissions. New learners can use SQLite for early lessons before changing the engine to MySQL.

On this page — Show page sectionsHide page sections

Create a database and dedicated user

Run in a MySQL administration tool with appropriate privileges

CREATE DATABASE django_demo CHARACTER SET utf8mb4;
CREATE USER 'django_user'@'localhost' IDENTIFIED BY 'replace-with-a-strong-password';
GRANT ALL PRIVILEGES ON django_demo.* TO 'django_user'@'localhost';
Replace the example password before use. Store real credentials in environment variables or a secrets manager; do not commit them to GitHub or print them in tutorial screenshots.

Configure DATABASES in settings.py

plus2net_demo/settings.py — read credentials from environment

import os

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": os.environ["DJANGO_DB_NAME"],
        "USER": os.environ["DJANGO_DB_USER"],
        "PASSWORD": os.environ["DJANGO_DB_PASSWORD"],
        "HOST": os.getenv("DJANGO_DB_HOST", "127.0.0.1"),
        "PORT": os.getenv("DJANGO_DB_PORT", "3306"),
        "OPTIONS": {"charset": "utf8mb4"},
    }
}

Putting database credentials directly into source code risks accidental exposure. Environment variables keep credentials out of the page’s code and avoid accidental source-control exposure. See the official Django MySQL backend notes.

Create the student app and model

Run from the folder containing manage.py

python manage.py startapp students

students/models.py — shared model used in the remaining database lessons

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    cl = models.CharField(max_length=20, db_column="class")
    mark = models.PositiveSmallIntegerField()
    gender = models.CharField(max_length=20)

    def __str__(self):
        return self.name

The model defines name, cl, mark and gender. The db_column="class" setting preserves the SQL column name class where existing examples need it. Django adds a primary key automatically unless configured otherwise.

Register the app

plus2net_demo/settings.py

# Add this app name to the existing INSTALLED_APPS list
"students",

Create and apply migrations

Generate and apply the student table migration

python manage.py makemigrations students
python manage.py migrate
python manage.py showmigrations students

makemigrations prepares schema changes as migration files; migrate applies them to the configured database. Run them in that order. Generate migration files with your installed Django version rather than copying migration output from another project.

Inspect the SQL migration

View SQL generated for the initial migration

python manage.py sqlmigrate students 0001

The SQL depends on your Django and MySQL versions. Table names generally follow app_model, such as students_student; do not assume an old example’s student_student or exact SQL will always match.

Check the database using Django shell

Open the Django shell

python manage.py shell

Check the model and query the first records

from students.models import Student
print(Student.objects.count())
print(Student.objects.order_by("id")[:5])

Next, learn how to insert a student using a validated form, insert batches, query and display rows or manage records using the admin interface.

Common MySQL configuration problems

  • ModuleNotFoundError: MySQLdb: install a compatible mysqlclient wheel/build for your Python environment.
  • Access denied: verify database user permissions, host and password.
  • Unknown database: create the database before running migrations.
  • Model table missing: check INSTALLED_APPS, makemigrations and migrate.
  • Database connection refused: verify MySQL is running and the host/port values are correct.

Additional database commands and checks

Validate project configuration

python manage.py check

Check the status of the students app migrations

python manage.py showmigrations students

Open the configured database client when available

python manage.py dbshell

Inspect a legacy database schema (for database-first projects)

python manage.py inspectdb

inspectdb is helpful when connecting Django to a database with existing tables. Generated models should be reviewed rather than pasted into production unchanged.

Illustration of non-secret variables; keep password out of public examples

# Environment variables for the DB credentials, shown as names only
DJANGO_DB_NAME=django_demo
DJANGO_DB_USER=django_user
DJANGO_DB_HOST=127.0.0.1
DJANGO_DB_PORT=3306

Verify that the configured database accepts a simple query

from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("SELECT 1")
    print(cursor.fetchone())

Expected output

(1,)

Django shell — insert one example record

from students.models import Student
Student.objects.create(name="Alex", cl="Four", mark=78, gender="male")

Count students with marks of 60 or above

from students.models import Student
print(Student.objects.filter(mark__gte=60).count())

Preview pending migration steps before applying them

python manage.py migrate --plan
For an established production database, inspect planned schema changes and arrange backups before applying migrations. Do not use tutorial credentials or sample data on live student records.

Frequently asked questions

Can I use SQLite instead of MySQL?

Yes. The Django ORM and model examples work with SQLite for local learning. For MySQL-specific behavior, configure a MySQL server.

Should I edit migration files by hand?

Generally no. Change models and run makemigrations, then inspect and review the resulting migration before applying it.

Should I create the SQL table manually?

Normally Django migrations create it. Mixing manual schema changes and migrations may cause inconsistent model state.

Previous: CSS, JavaScript, jQuery and static files

Next: Insert form data

Browse the complete Django tutorial series.

Additional references

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer