Deploying Django App To Railway.app
Issues with Deploying Django App to Railway platform resolved...
Table of contents
- Railway app
- Starting with Railway.app
- Error : Build Failed
- My Project name is mysite, and I utilized the python virtualenv for this tutorial.
- Solution 1: Head to the terminal and create a python virtual environment to help manage the codes
- Solution 2: Activate the Virtual Environment
- Solution 3: Download the needed packages into the virtual environment
- Solution 6: Create a .env file in your project
- Solution 7: Open the .venv folder which is the virtual environment you recently created, look for the .gitignore file and add these codes
- Solution 8 : Configuring the Postgresql Database on railway to work with your Django Application
- Solution 9 : Configurations of the settings.py file of your project
- Solution 10 : Run migrations on the new PostgreSQL database
- Solution 11 : Update the Code Changes to your GitHub to allow automatic redeployment of your Railway App
In this article, you will be taken through the exhaustive process of deploying your Django application to the Railway app and linking it with the PostgreSQL database which can be added from the railway cloud platform for free. The deployment usually comes with a lot of errors which can be boring to beginner and advanced developers alike, but this article seeks to help resolve these errors. Let's dive in.
Railway app
Starting with Railway.app
The railway platform comes with a lot of great features which makes it one of the best options for upcoming Django Developers out there to work with. You can get started by clicking on the link below
You can get your Django applications running on the railway in one of two ways which can be :
Build Django as a Template
Connect as existing Django Project on your Github repository to the railway.
Once you click on the New Project it shows you, you see the options that match your taste as displayed below
If you decide to Deploy a template, you have just a few configurations to make since the railway platform would have performed most of the important configurations automatically. It creates a Django application linked to your GitHub which you can then clone to improve on locally.
However, let's use the Deploy from GitHub repository option since it's likely you already have your projects on GitHub.
Follow the prompts from the railway and in a matter of seconds, it starts building the Django application you linked to and it's just most probable that your build fails since it's not yet properly configured.
Error : Build Failed
You may clone the GitHub repository locally with the code below.
git clone https://github.com/<username>/<repository name>.git
In this tutorial, my choice of IDE is Visual Studio Code Editor.
My Project name is mysite, and I utilized the python virtualenv for this tutorial.
Solution 1: Head to the terminal and create a python virtual environment to help manage the codes
virtualenv .venv
Solution 2: Activate the Virtual Environment
on Windows,
.venv\Scripts\activate
on Mac,
.venv\bin\activate
Solution 3: Download the needed packages into the virtual environment
(.venv) pip install django
(.venv) pip install gunicorn
To know your needed packages for the project, run the command below
(.venv) pip freeze > requirements.txt
This creates a file called requirements.txt which adds all needed packages for the projects with their respective versions. If you have it already, you can still run the code occasionally to update it whenever you install a new package with a pip command.
The requirements.txt file typically appeears as the diagram shown below
Solution 5 : Create a Procfile
Within the folder of your main project, create a procfile and add the content below
web: python manage.py migrate && gunicorn <your project name e.g mysite>.wsgi
Please note that the Procfile has no file extension
Solution 6: Create a .env file in your project
In your settings.py, delete the SECRET_KEY variable which has been most likely exposed by now. You need to create a new one with the code below in any python terminal.
import secrets
secrets.hex_token(24)
This helps you generate a new random secret key that you can utilize for the project.
Copy the key without quotes and save in a variable called SECRET_KEY
Add this secret key to your .env file
Solution 7: Open the .venv folder which is the virtual environment you recently created, look for the .gitignore file and add these codes
*.env
*db.sqlite3
Solution 8 : Configuring the Postgresql Database on railway to work with your Django Application
Ordinarily, Django comes with the sqlite3 database which can be utilized locally. However for production purpose its advisable to utilise the popular relational database which is postgresql which can be utilized freely from railway platform and used as the replacement database for sqlite3.
Simply head over to your railway platform and follow the prompts to add the PostgreSQL database to your project. All that is then needed from it are its details which will be utilized for connection to it.
Once you click on the PostgreSQL, you click on the copy icon , so you can copy the PosgreSQL Connection URL and head back to your Code Editor e.g VSCode
Update your .env file by adding the DATABASE_URL
#You .env now looks like this
#Don't add quotes to the values of the variables
SECRET_KEY=.......
DATABASE_URL=........
Solution 9 : Configurations of the settings.py file of your project
Update the settings.py file of your project with the following codes
#This line helps in linking the details of your .env to the settings.py file
from pathlib import Path
import os
from dotenv import load_dotenv
#This line is to help configure your project file and to make the .env file be recognized
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(os.path.join(BASE_DIR,".env"))
#SECURITY WARNING: don't run with debug turned on in production to avoid security breaches and making your boring errors be seen by users
DEBUG = False
#This allows the railway app to connect with your project.
ALLOWED_HOSTS = ["*"]
#This line helps to link your secret key
SECRET_KEY=os.getenv('SECRET_KEY')
#This code updates the middle ware to help whitenoise package handle your static files well
MIDDLEWARE={
'......'
'whitenoise.middleware.WhiteNoiseMiddleware',
'...'
}
#You can comment the details of the sqlite3 database or delete it since you are not using it , to avoid unnecessary interference with the new PostgreSQL
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
'''
#update this line of code, because its needed for the PostgreSQL database to function properly
DEFAULT_AUTO_FIELD='django.db.models.BigAutoField'
#This lines helps to link your database details
import dj_database_url
DATABASE_URL=os.getenv("DATABASE_URL")
DATABASES={
"default":dj_database_url.config(default=DATABASE_URL,conn_max_age=1800),
}
# Add this line of code to prevent error caused by Django 40 version about trusted origins
CSRF_TRUSTED_ORIGINS=['https://mysite-django-production.up.railway.app']
Solution 10 : Run migrations on the new PostgreSQL database
Head over to the terminal and run the following lines of codes to make the new Database Functional
(.venv) python manage.py makemigrations
(.venv) python manage.py migrate
Solution 11 : Update the Code Changes to your GitHub to allow automatic redeployment of your Railway App
For users of VSCode Editor, your code editor can have been automatically linked with your GitHib Repository. However for non-users, the point is to update your code changes to your GitHub repository
$ git init
$ git add .
$ git commit -m "updates"
$ git push origin <main or master>
By now most of the errors you would ever encounter in the process of your deployment has been resolved. But in case there are any other you come across, feel free to get across to me.
I am open to your questions and collaborations...