To make full use of Django, also on a larger scale, it is essential to connect Django to a database. A database service that is particularly useful is the Oracle Cloud Database. Here, you can configure different types of databases like classic SQL databases but also data warehouses. On top, there are several options available as always free service to kickstart your project for free. However, connecting Django to a database service can be quite an obstacle. That’s why I want to share my experience with you.
For this article, I will assume that you already created a database on Oracle Cloud. There are several good tutorials on the internet, like this one. Once your set up your autonomous database, you need to download the connection wallet. You can find the wallet under Database connection. There you need to select Wallet type: Instance wallet and then click download.
Next, you need to download the oracle instant client for your database version. You find the database version on the General Information page of your database. The instant client download page is here. On this page you first need to select your operating system. Then, you can choose the matching version and download the Basic (zip) file. You can store and unpack it wherever you want in your OS. If you're using MAC, you can also brew install instantclient-basic and then install it with /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru/install_ic.sh.
Now to Django. of course you need to set up Django by installing it e.g. with pip etc. You can find a good guide to get started here. Once you're all set with Dajngo, you need to pip install cx_oracle. Next, you need to edit the settings.py in the main Django directory in your project. E.g.:
Here you need to edit or add the DATABASES dictionary. It should look like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'key_from_tnsnames',
'USER': my_user,
'PASSWORD': 'my_password'
}
}
The name needs to equal one of the variable names in the tnsnames.ora file from your wallet. Also the username and password of your database need to be provided. At last, you need to add the following to the main function of manage.py:
cx_Oracle.init_oracle_client(lib_dir="/path-to-instant-client-folder")
To add the Django database model to your database and see if the connection works, you can finally run python manage.py migrate in your projects command line. When you check the database e.g. in SQL Developer afterwards, you will notice that several new tables have been added. Also, you should be able to run python manage.py runserver without running into any errors.