Welcome back to our Django Tutorial! Today, we're diving into the world of Database Configuration. This is a crucial step in setting up your Django project, as it allows us to store and manage data effectively. Let's get started! π
In simple terms, Database Configuration is the process of telling Django which database to use, how to connect to it, and the settings for that database. Django supports several databases out-of-the-box, including SQLite, MySQL, and PostgreSQL.
Before we start, ensure you have Python's psycopg2 (for PostgreSQL) or mysqlclient (for MySQL) packages installed. If not, you can install them using pip:
pip install psycopg2-binary # For PostgreSQL
pip install mysqlclient # For MySQLNext, open your Django project's settings.py file. Scroll down to the DATABASES section. Here, we'll specify the name of the database backend and the connection details for our database.
Here's an example for PostgreSQL:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'my_database', # Your database name
'USER': 'my_user', # Your database user
'PASSWORD': 'my_password', # Your database password
'HOST': 'localhost', # Your database host (usually localhost)
'PORT': '', # Leave this empty for default port
}
}For PostgreSQL, you'll need to create the database manually. You can do this using the createdb command in the terminal:
createdb my_databaseFor MySQL, you can create the database using the mysql command in the terminal:
mysql -u root -p
CREATE DATABASE my_database;Now that our database is set up, we need to create the tables for our Django models. We do this by running migrations.
First, ensure your app is selected:
cd my_appThen, run the following command to apply migrations:
python manage.py migrateTo confirm that everything is working correctly, let's create a simple model and check if we can save it to the database.
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.nameAfter adding this code to your app's models.py, run the following command:
python manage.py makemigrations
python manage.py migrateNow, let's create an instance of MyModel and save it:
python manage.py shell
from my_app.models import MyModel
my_model = MyModel(name='Test')
my_model.save()If everything is set up correctly, you should see your new model instance in the database!
What is the purpose of the DATABASES section in Django's `settings.py` file?
That's it for today! With this lesson, you've learned how to configure a database in Django. Stay tuned for more lessons in our Django Tutorial! π