A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Production
How To Create A Blog in VS Code — Part XI — DjangoSeries Episode # 14
In this post we’re going to learn how to deploy our Django application using Heroku so that anyone with internet access can use it within a browser.
When it comes to deploying an application, there are usually two options:
A VPS or a PaaS (platform as a service).
This post will show you my recipe (PSHPs — v1.0) for deploying our application to production on a PaaS like Heroku.
Let’s get started!
Motivations
If you already deploy some web page to a Linux server then you would have noticed that that took a lot of time and also requires you to be familiar with a little bit of system administration and things like that in order to get your application up and running.
Heroku abstracts a lot of that away and allows us to get our application deployed more easily without needing to set up our own web servers and firewalls and stuff like that and they also have a free tier that you can use so that you can actually get your application deployed without paying any money :).
Deployment
First let’s see two concept: development process & military deployment .
Development is the process or result of making a basic design gradually better and more advanced.
The deployment of troops, resources, or equipment is the organization and positioning of them so that they are ready for quick action.
We have made a tremendous effort to develop gradually our jungleDev site in the localhost.
This process takes time, work, and passion.
Now we have to deploy our site behind a front-line trench: the cloud!
This is a Big Bet (poker)!
Once you are in the internet security must be your first concern.
Malware such as spyware, ransomware, viruses and worms, you know…
Cisco reports that ransomware, once activated, can block access to key network components…
Django is as secure as any web framework can be, but the whole platform security depends on the proper use of the tools we choose, and thus is more a matter of developer skills.
Now I have a bit of experience under my belt. These are my last three Heroku projects:
https://j3djangoapp.herokuapp.com/
https://jungletronics.herokuapp.com/
https://jungledjango.herokuapp.com/
Ladies and gentlemen, may I present you my brand new recipe:
Python Strategic Heroku Pillars Script (PSHPs v1.0)
We’ve compiled essentials steps to help you quickly push a Python site to Heroku production:
Follow me:
PSHPs - v1.0Step#01-Create Heroku Project;
Step#02-Activate Heroku & the Control Version System - CLI & GIT;
Step#03-Link git repository to Heroku;
Step#04-Files: backup, gitignore, runtime, Procfile & requirements;
Step#05-Install Gunicorn (WSGI HTTP Server);
Step#06-Goto Settings.py: change debug status;
Step#07-Register the allowed hosts;
Step#08-Deal w/ Middleware - WhiteNoise & staticfiles;
Step#09-Database - install pg, dj & psycopg2;
Step#10-Git Push Master to Heroku;
Step#11-Migrations;
Step#12-Deploy Buildpacks, Env. Variables & Cloudinary DB;
Step#13-Create a superuser;
Step#14-Test on-air services (email, login, logout, etc);
01#Step — Create Heroku Project
First thing first, after you create an account with Heroku, you can log in to your dashboard and create a new app:
02#Step — Activate Heroku & the Control Version System — CLI & GIT;
Install these on your machine:
Git installation
Heroku CLI
GoTo Heroku Deploy tab and follow this steps:
Next, open up the vscode Terminal, and type:
git config --global user.email "<your_emai>@gmail.com"git config --global user.name "<your username>"heroku login
» Warning: heroku update available from 7.53.0 to 7.59.2.
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/b0761a5a-9a72-46a8-b548-da163afc99fe?requestor=SFMyNTY.g2gDbQAAAA8xNzkuMTU1LjI0Ny4yMzFuBgDQAPsSfwFiAAFRgA.tCgM5QzGCwkXcjKp26PvJWBNvpikSOdOcCoOAI494Qc
Logging in... done
Logged in as ...@gmail.com
03#Step — Link git repository to Heroku;
Initialize a git repository in a new or existing directory
cd my-project/
git init
heroku git:remote -a jungledev
heroku git:remote -v
From now on follows a detailed walk-through of the process for Python developers to deploy their local application to Heroku.
04#Step — Files: backup, gitignore, runtime, Procfile & requirements;
settings.py
👉 create a backup extensions settings.bak
gitignore.txt
👉 Download file:here
runtime.txt
👉 create a file, type: python-3.9.7
Procfile
👉 New file: web: gunicorn django_project.wsgi --log-file -
📝 no extensions
requirements.txt
👉 On Terminal type:
pip list --format=freeze > requirements.txt
📝 about pip freeze requirements.txt
visit this link
05#Step — Install Gunicorn (WSGI HTTP Server);
GoTo Terminal and type:
pip install gunicorn
06#Step — Goto Settings.py
: Set Environment Variables;
The easiest way to do this is simply set the Heroku value as follows:
heroku config:set DEBUG_VALUE="False"
Then in your settings.py
test the string value that you stored as follows:
DEBUG = (os.environ.get('DEBUG_VALUE') == 'True')
Now set your DEBUG_VALUE
in your system environment.
Since DEBUG_VALUE
is set to "False", DEBUG
will be False in production.
Also the secret key shouldn’t be something that we put in our code potentially for other people to see so I’m going to create an environment variable for the secret key
Got to python interpreter (just type python in your Terminal), and type:
import secrets
secrets.token_hex(24)<SECRET_KEY generate goes to your environment as well :)>exit()
Goto Heroku, type(option: HEROKU_GUI see vid:):
heroku config:set DEBUG_VALUE="True"heroku config:set SECRET_KEY="<YOUR_SECRET_KEY>"heroku config:set EMAIL_USER="<YOUR_EMAIL_USER>"heroku config:set EMAIL_PASS="<YOUR_EMAIL_PASS>"
GoTo settings.py and comment out the old SECRET_KEY, and type:
import osSECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG_VALUE = os.environ.get('DEBUG_VALUE')
07#Step — Goto Settings.py
: Register the allowed hosts;
ALLOWED_HOSTS = ['127.0.0.1','jungledev.herokuapp.com' ]
08#Step — Deal w/ Middleware — WhiteNoise & staticfiles;
In your Terminal, type:
pip install django-heroku
In your settings.py, type:
import django_heroku
And at the very end:
django_heroku.settings(locals())
By just adding that in that’s going to automatically set a lot of those configurations for us. Good!
Django Heroku package is going to automatically configure our database URL and we’ll also take care of connecting our static assets to G unicorn using a package called white noise.
WhiteNoise radically simplified static file serving for Python web apps.
Installation, in your Terminal type:
pip install whitenoise
Now in settings.py
:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# ...
]
In settings.py
save this config too:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
09#Step — Database — install pg, dj & psycopg2;
Heroku Postgres is a managed SQL database service provided directly by Heroku.
We can provision it with the following CLI command:
$ heroku addons:create heroku-postgresql:<PLAN_NAME>
For example, to provision a hobby-dev plan database:
$ heroku addons:create heroku-postgresql:hobby-dev
Now run Heroku PG we can see there it shows us a bit more about that database:
heroku pg
So we can see that it has for the rows zero out of ten thousand so the free tier does have a ten thousand row limit. Just Fine!
Install on your machine PostgreSQL
The World’s Most Advanced Open Source Relational Database. Heroku uses it.
Install psycopg2 — Python-PostgreSQL Database Adapter
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
In your Terminal type:
pip install psycopg2
10#Step — Git Push Master to Heroku;
But before let’s run freeze command:
pip list --format=freeze > requirements.txt
Now type:
git status
git add -A
git commit -m "Running PSHPs v1.0 from 1 to 10"
git push heroku master
📝 Python Strategic Heroku Pillars Script (PSHPs v1.0)
Right after the code run, type:
heroku open
Hope for the best, and prepare for the worst…🙄
11#Step — Migrations;
Execute steps # 2,3, and 4 of this post
python manage.py makemigrations
python manage.py sqlmigrate blog 0001
python manage.py migrate
Businesses lose millions of dollars every year due to inadequate migrations. Don’t let a bad migration leave your business struggling.
In your Terminal, type:
heroku run python manage.py migrate
12#Step — Deploy Buildpacks, Environment Variables & Cloudinary DB
GoTo Heroku dashboard and in Settings
tab include python
as Buildpacks
.
Create and Modify Environment Variables on Windows (see right at the end of this video ;)
Fine, now at Resources
tab add-ons
find:
Cloudinary - Starter - Free - Submit Order Form
Cloudinary is a SaaS technology company headquartered in Santa Clara, California, with offices in Israel, England, Poland, and Singapore. The company provides cloud-based image and video management services. It enables users to upload, store, manage, manipulate, and deliver images and video for websites and apps.
Click on it and it will open Cloudinary dashboard.
To gather the identifying information needed to authenticate go to settings ico and fill:
CLOUDINARY_STORAGE = {
'CLOUD_NAME': '<your_cloud_name>',
'API_KEY': '<your_api_key>',
'API_SECRET': '<your_api_secret>'
}
Now save this in your Settings.py plus:
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
And in your installed apps:
INSTALLED_APPS = [
...
'cloudinary_storage',
'cloudinary',
]
Now the last operation:
pip install cloudinary django-cloudinary-storage
let’s run freeze command:
pip list --format=freeze > requirements.txt
Now type:
git status
git add -A
git commit -m "Adding cloudinary add-on"
git push heroku master
Type this at the end of settings.py
:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
13 #Step — Create a superuser again and visit your site on line!
heroku run python manage.py createsuperuser
14 #Step —Test on-air services (email, login, logout, etc);
Run the script as explained in this post to upload all dummies post
Now just enjoy!
👉Here is the result: https://jungledev.herokuapp.com/👈
All right folks!
Congratulations! We Have achieved our goals after fourteen episodes!
Our Mission Statement, Make Our Own Website on Heroku, Was Accomplished!
To like all parts of our strategic episodes, help we focus our team on what we need to work on, and what we don’t need to work on.
I know these episodes were numerous but hopeful it will be useful.
See you around!
Bye!
👉 git
Credits & References
Python Django Tutorial: Full-Featured Web App by Corey Schafer
Heroku by heroku.com
Cloudinary by cloudinary.com
Heroku Postgres by devcenter.heroku.com
Como colocar foto no perfil do Heroku via Gravatar by Ana Paula Carneiro
Heroku Debug Flag not stopping django debugging by stackoverflow.com
“SMTP AUTH extension not supported by server” error while trying to send email though django app using gmail by stackoverflow.com
Related Posts
00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries
01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code
02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!
03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!
04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start! — Part_I
05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II
06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III
07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV
08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V
09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI
10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII
11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII
12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX
13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X
14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio— Part_XI (this last one…whew!)
HowTo Run this Tutorial - From the Scratch - In your Machine:)Annotations: Quick Start - video #TakeTheFirstStepToLearnDjango0 - Download DJG_<previous>/Django_project from my git repo;
1 - On your desktop, create a dir and named it as Tutorial_#;
2 - Inside this paste the previous Django_project file;
3 - GoTo vscode Terminal (command prompt) and ...
4 - Run this quick_script
(copy/paste inside you terminal and hit enter and wait until
Pillow is up and running...):python -m venv djangoEnv
djangoEnv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install django
python -m django --version
pip install django-crispy-forms
pip install Pillow5- GoTo Step#01 of this tutorial.And you are good to go!
Notes:
For Heroku shell:heroku run python manage.py shellIn case you want to delete superuser:Delete Superuser from the Heroku shell:> python manage.py shell
$ from django.contrib.auth.models import User
$ User.objects.get(username="j3", is_superuser=True).delete()
We remain forever neoplastic. We remain forever changeable, and healable by experiences of being understood.
Sarah Peyton
[ChatGPT]
Explain: "We remain forever neoplastic"
ChatGPT
The phrase "We remain forever neoplastic" suggests
that the speaker or the subject being referred to
is in a state of perpetual change or transformation,
akin to the characteristics of neoplasticity.
Neoplasticity is a term commonly used in the field
of biology and medicine to describe the abnormal
growth and development of cells, particularly in
the context of cancer. Neoplastic cells exhibit
uncontrolled proliferation and have the ability
to invade surrounding tissues. They constantly
evolve and adapt, which contributes
to their malignant nature.
By using the phrase "We remain forever neoplastic,"
the speaker is likely implying that they or the subject
in question possess a similar quality of continuous
evolution, adaptability, or transformation.
It suggests a dynamic and ever-changing nature,
possibly emphasizing the ability to adapt,
learn, and grow in various aspects of life.
It might imply that they do not settle into a
fixed or static state, but rather
embrace constant change and development.
Date: jun 2023