0
0
Djangoframework~5 mins

Database configuration in Django

Choose your learning style9 modes available
Introduction

Database configuration tells Django where and how to save your app's data. It connects your app to a storage place.

When starting a new Django project and you need to store user info.
When switching from one database type to another, like from SQLite to PostgreSQL.
When deploying your app and connecting it to a production database.
When setting up multiple databases for different parts of your app.
When customizing database settings like connection options or time zones.
Syntax
Django
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

ENGINE tells Django which database type to use.

NAME is the database file or database name.

Examples
Example for connecting to a PostgreSQL database with user and password.
Django
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
Example for connecting to a MySQL database.
Django
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': 'secret',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
Example using SQLite with a custom file name.
Django
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'mydatabase.sqlite3',
    }
}
Sample Program

This example sets up a simple SQLite database configuration and prints the engine and file path.

Django
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

print(f"Database engine: {DATABASES['default']['ENGINE']}")
print(f"Database file: {DATABASES['default']['NAME']}")
OutputSuccess
Important Notes

Use BASE_DIR to keep database files inside your project folder.

For production, avoid using SQLite; use PostgreSQL or MySQL instead.

Keep your database passwords safe and do not hardcode them in public code.

Summary

Database configuration connects your Django app to a data storage.

Set ENGINE and NAME to tell Django which database to use.

Use different settings for development (SQLite) and production (PostgreSQL/MySQL).