DEV Community

Diego Ramos
Diego Ramos

Posted on

Connect Django to ElephantSQL

Created demo project folder

mkdir connectSql
Enter fullscreen mode Exit fullscreen mode

CD into the directory and start a virtual environment using venv:

# create virtual environment
python3 -m venv virt

# activate virtual environment
source virt/bin/activate
Enter fullscreen mode Exit fullscreen mode

Install django in your virtual enviroment

pip install django
Enter fullscreen mode Exit fullscreen mode

Install a PostgreSQL adapter to be able to connect to ElephantSQL(PostgreSQL as a service). We will install psycopg2

# for beginners that don't want to deal with extra dependencies 
pip install psycopg2-binary

# for production
pip install psycopg2
Enter fullscreen mode Exit fullscreen mode

I decided to install psycopg2 on my Linux Mint 21.2 fresh installation and also had to install libpq-dev to fix the missing pg_config error during psycopg2 installation

read more about the differences in the official documentation

Install django-environ to use environment variables and hide sensitive information when pushing the code to GitHub

pip install django-environ
Enter fullscreen mode Exit fullscreen mode

Start a django project

Read more in how to start a django project

django-admin startproject demo-project
Enter fullscreen mode Exit fullscreen mode

CD into project and create the app, in this example I called it ‘website’

python3 manage.py startapp website
Enter fullscreen mode Exit fullscreen mode

create a .env file in the same folder as settings.py

touch .env
Enter fullscreen mode Exit fullscreen mode

We now need to create an instance of our database

ElephantSQL login page

  • Create a new instance

ElephantSQL create new instance

  • Select a plan (Tiny Turtle(Free)) and a name

ElephantSQL new instance select plan and name

  • Confirm new instance

confirm creation of the new instance

  • Select your newly created instance

select your newly created instance

  • In details find your URL, as it has all the information we will need

instance details

Add the database information you just copied to the .env file

💡 The URL from ElephantSQL has the following information:
postgres://username:password@hostname/databasename

DATABASE_NAME=databasename
DATABASE_USER=username
DATABASE_PASS=password
DATABASE_HOST=hostname
DATABASE_PORT=5432
Enter fullscreen mode Exit fullscreen mode

💡 Make sure to add your .env file to .gitignore

Now back to our project, update settings.py

# we need to import and inititiate environ
import environ

# Init environ variables
env = environ.Env()
environ.Env.read_env()


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
Enter fullscreen mode Exit fullscreen mode

Add website to installed apps, and update the DATABASES information with the database information we added to the .env file

# add website
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
        'website'
]
DATABASES = {
    'default': {
        # change sqlite3 for postgresql
        'ENGINE':'django.db.backends.postgresql',
        'NAME': env('DATABASE_NAME'),
        'USER': env('DATABASE_USER'),
        'PASSWORD': env('DATABASE_PASS'),
        'HOST': env('DATABASE_HOST'),
        'PORT': env('DATABASE_PORT')
    }
}
Enter fullscreen mode Exit fullscreen mode

Run migrate

python3 manage.py migrate   
Enter fullscreen mode Exit fullscreen mode

If everything is ok you should see this:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
Enter fullscreen mode Exit fullscreen mode

You can also go to your database in ElephantSQL and check that the tables were created

instance SQL Browser

Top comments (0)