Connect Django to ElephantSQL
Tags: beginners, django, webdev, python
Published: 2023-08-04 14:06:45

**Created demo project folder**

```python
mkdir connectSql
```

**CD into the directory and start a virtual environment using [venv](https://docs.python.org/3/library/venv.html):**

```python
# create virtual environment
python3 -m venv virt

# activate virtual environment
source virt/bin/activate
```

**Install django in your virtual enviroment**

```python
pip install django
```

**Install a PostgreSQL adapter to be able to connect to ElephantSQL(PostgreSQL as a service). We will install [psycopg2](https://www.psycopg.org/docs/install.html)**

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

# for production
pip install psycopg2
```

> 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](https://www.psycopg.org/docs/install.html#psycopg-vs-psycopg-binary)
> 

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

```python
pip install django-environ
```

**Start a django project**

> Read more in how to start a [django project](https://realpython.com/django-setup/)
> 

```python
django-admin startproject demo-project
```

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

```python
python3 manage.py startapp website
```

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

```python
touch .env
```

**We now need to create an instance of our database**

- Go to [ElephantSQL webpage](https://www.elephantsql.com/) and create a new account
        

![ElephantSQL login page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8r6z4zhbuphmhrd4p5c.png)
    

- Create a new instance
    
![ElephantSQL create new instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tspcvxiaif34zpj58gzf.png)
    
- Select a plan (Tiny Turtle(Free)) and a name

![ElephantSQL new instance select plan and name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdd012j67nin22ov3a78.png)

- Confirm new instance

![confirm creation of the new instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cncfccupka6wutpckdzd.png)

- Select your newly created instance

![select your newly created instance ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vl1qij4606zlzm7qyktr.png)

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

![instance details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzqooos77h527usorl75.png)

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

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

```python
DATABASE_NAME=databasename
DATABASE_USER=username
DATABASE_PASS=password
DATABASE_HOST=hostname
DATABASE_PORT=5432
```
<aside>
💡 Make sure to add your .env file to .gitignore
</aside>

**Now back to our project, update settings.py**

```python
# 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',
    }
}
```

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

```python
# 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')
    }
}
```

**Run migrate**

```python
python3 manage.py migrate   
```

**If everything is ok you should see this:**

```python
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
```

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

![instance SQL Browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqk6k7n9nfckoc4xzrlj.png)