Use a Database with Django#
The Django container you put into production last week contains a SQLite database. SQLite is a great database for simple applications but it doesn’t scale. Databases in cloud applications is a complicated subject that we’ll start thinking about this week. The first thing to know is that your precious application data cannot live in a container’s writable layer!
Install the Python Dependencies#
Your dev box needs the Python libraries that enable Python to use Postgres, just like it needed the Django libraries. Before Django can use Postgres install the psycopg2-binary
package in Python:
$ pip install psycopg2-binary
Now let’s bring up the Python REPL and make sure we can connect to a running Postgres container:
$ python3
>>> import psycopg2
>>> con = psycopg2.connect("host='localhost' user='postgres' password='django'")
>>> cursor = con.cursor()
>>> cursor.execute("select * from mydata;")
>>> for row in cursor.fetchall():
... print(row)
...
(1, 'foo')
>>> quit()
Error
Do you get an error connecting? Check the Postgres container.
Configure Django#
Django’s database configuration is found in mysite/settings.py
. Alter the DATABASES
variable with the new configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mysite',
'USER': 'postgres',
'PASSWORD': 'django',
'HOST': 'localhost',
},
}
Warning
The database contains all of the user and other information from Django. When you switch databases all of the information is lost. You now have to re-initialize the new database which will be empty to start with.
Let’s get Django to rebuild the new database:
$ export SECRET_KEY=nonsense-for-now # Needed for our app!
$ python3 ./manage.py migrate
$ python3 ./manage.py createsuperuser
Username (leave blank to use 'mmatera'): student
Email address: student@cabrillo.edu
Password:
Password (again):
The password is too similar to the email address.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
Congratulations! You should be able to run and see your migrated Django installation:
$ python3 manage.py runserver 0.0.0.0:8000
Updating Your Container#
If you rebuild and rerun your container now there will be a problem. Containers can’t use localhost
to connect to services on the host. This is by design. In order to make your Django container connect to your Postgres container you need to use Docker networking. That is the subject of the next lab.