Intergrated and connect postgreSQL third party on railways for Django app

Soedarhana
3 min readAug 8, 2023

--

Previously I have been stuck for connecting my local project django as default using the database mysql3. Trying to find best recommended database for my django app, and then I got many developer using the postgresql for their our app, so I decided to use it too. Here I use a third party to use postgresql. I thank Railways in advance for providing it for free. So how do I integrate our django application with postgresql as a database container via railways?

PostgreSQL on Railways app

What tools do we need is:

  1. PostgreSQL database using (Railways)
  2. Psycopg2-binary
  3. Django environ
  4. .env file

I assume you already have your own django project and django app, Then look for the settings.py file in your project directory and find the “DATABASES” syntax. By default it will look like this:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}

We will integrate and modify this Django default setting and change to postgreSQL from Railways, see to my own site how you create the database postgreSQL here soedarhana.id

Find the connect tab or Variable from railways

Going to the connect tab, copy the all of variable provided by railways to the “DATABASES” your Django app. And typing like this below :

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'railway',
'USER': 'postgres',
'PASSWORD': 'YOUR_PASSWORD',
'HOST': 'YOUR_HOST',
'PORT': 'YOUR_PORT',
}
}

Why i add the “psycopg2” after postgresql_ it will allowed you to connect and interact with PostgreSQL databases. Psycopg2 is a popular Python library. Easy for using it on windows, typing on your terminal or text IDE with this command:

pip insall psycopg2-binary

Next step is add the additional file “.env” file and the contents are data that displays your postgresql database configuration. Should look like this :

.env file

So now you can put the variable on railways to .env file, after that you need Django environ. Django environ is the Python package that allows you to use Twelve-factor methodology to configure your Django application with environment variables. To install additional Django environ do this syntax below:

pip install django-environ

and try to execute for the migrate your database, before your execute the migrations or migrate, it will good if you check with :

py manage.py showmigrations

After that, make migrations and migrate it. If your connections succes, you will see the many table on your Railways Data.

sign that you have successfully connected

Congratulations you have successfully connected postgresql from railways to your django application. Find another way my tutorial through soedarhana.id

--

--