This sample application demonstrates how to connect to a PlanetScale MySQL database, create and run migrations, seed the database, and display the data.
For the full tutorial, see the Django PlanetScale documentation.
- Clone the starter Django application:
git clone git@github.com:planetscale/django-example.git
cd django-example
- Start the virtual environment
python3 -m venv env
source env/bin/activate
For Windows, use env/Scripts/activate
.
- Install the required packages:
pip install -r ./requirements.txt
-
Sign up for a free PlanetScale account and create a new database.
-
Click the "Connect" button to generate credentials for database branch (
main
is default). Select "Django" from the language dropdown and copy the values in the sample.env
file. -
Modify your
.env
file in your Django app with the values from the previous step:
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST=
DB_PORT=
MYSQL_ATTR_SSL_CA=
Note: The value for
MYSQL_ATTR_SSL_CA
may differ depending on your operating system.
- In the
mysite/settings.py
file, scroll down and look for theDATABASES
object. Replace it with the following:
DATABASES = {
'default': {
'ENGINE': 'django_psdb_engine',
'NAME': os.environ.get('DB_NAME'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'OPTIONS': {'ssl': {'ca': os.environ.get('MYSQL_ATTR_SSL_CA')}}
}
}
- Change directory and run the migrations and seeder with:
cd mysite/
python3 manage.py migrate
- Start the server with:
python3 manage.py runserver
- Navigate to
localhost:8000/products
to see a list of data from the products table.