How to Configure Database in settings.py in Django
To configure a database in Django, edit the
DATABASES dictionary in your settings.py file. Specify the ENGINE, NAME, and other connection details like USER, PASSWORD, HOST, and PORT depending on your database type.Syntax
The DATABASES setting in settings.py is a dictionary where each key is a database alias (usually default). Each value is another dictionary with keys like ENGINE (database backend), NAME (database name or path), USER, PASSWORD, HOST, and PORT.
This structure tells Django how to connect to your database.
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', # Database backend
'NAME': 'mydatabase', # Database name
'USER': 'myuser', # Database user
'PASSWORD': 'mypassword', # User password
'HOST': 'localhost', # Database host
'PORT': '5432', # Database port
}
}Example
This example shows how to configure a PostgreSQL database in settings.py. Replace the values with your actual database details.
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'exampledb',
'USER': 'exampleuser',
'PASSWORD': 'examplepass',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}Output
When running Django commands like 'python manage.py migrate', Django connects to the configured PostgreSQL database using these settings.
Common Pitfalls
- Wrong ENGINE string: Using an incorrect backend string causes connection errors. For example, use
django.db.backends.sqlite3for SQLite,django.db.backends.postgresqlfor PostgreSQL. - Missing database file for SQLite: For SQLite,
NAMEmust be the full path to the database file orBASE_DIR / 'db.sqlite3'. - Incorrect credentials: Wrong
USERorPASSWORDwill prevent connection. - Not installing database driver: For PostgreSQL, you must install
psycopg2orpsycopg2-binary.
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgres', # Wrong: should be 'postgresql'
'NAME': 'mydb',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Correct version:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': 'localhost',
'PORT': '5432',
}
}Quick Reference
Here is a quick summary of common ENGINE values and their typical NAME values:
| Database | ENGINE value | NAME value example |
|---|---|---|
| SQLite | django.db.backends.sqlite3 | BASE_DIR / 'db.sqlite3' |
| PostgreSQL | django.db.backends.postgresql | mydatabase |
| MySQL | django.db.backends.mysql | mydatabase |
| Oracle | django.db.backends.oracle | XE |
Key Takeaways
Edit the DATABASES dictionary in settings.py to configure your database connection.
Set the ENGINE key to the correct backend string for your database type.
Provide accurate NAME, USER, PASSWORD, HOST, and PORT values for connection.
Install required database drivers like psycopg2 for PostgreSQL.
For SQLite, use the full path to the database file in NAME.