Building a Blog with Django and Heroku: Part 3 – Deployment

Building a Blog with Django and Heroku: Part 3 – Deployment

Welcome to Part 3 in our series on building a blog with Django and deploying it using Heroku and Cloud9. In Part 1, we set up our project and created the initial Django models. In Part 2, we built out our views, templates, and administrative interface. Now, it’s time for the exciting step: deploying our application to the web so the world can see it.

This guide walks you through the deployment process using your specified package versions:

  • asgiref==3.10.0
  • dj-database-url==3.0.1
  • Django==4.2.26
  • gunicorn==23.0.0
  • packaging==25.0
  • psycopg2-binary==2.9.11
  • sqlparse==0.5.3
  • typing_extensions==4.15.0

We’ll cover setting up these dependencies, configuring your project, and handling static files and database migrations on Heroku—all aligned with your project’s requirements.

Deploying a web application can seem intimidating, but Heroku streamlines the workflow. Let’s get started.

About Your requirements.txt Packages

Here’s a quick explanation of each package and its role in your Django deployment:

  • asgiref==3.10.0: Provides an interface for Python’s ASGI (Asynchronous Server Gateway Interface), which enables async support in Django and other web frameworks. Required by Django for managing asynchronous tasks and communication.
  • dj-database-url==3.0.1: Simplifies database configuration by parsing the DATABASE_URL environment variable, making it easy to switch between different databases (like moving from SQLite locally to PostgreSQL on Heroku).
  • Django==4.2.26: The main Python web framework powering your application. Version 4.2.26 is a long-term support release, providing stability, performance, and security.
  • gunicorn==23.0.0: A production-grade WSGI server for running Django applications. Heroku uses Gunicorn to serve requests instead of Django’s built-in development server.
  • packaging==25.0: Offers utilities for Python package version and dependency management. Some other dependencies may rely on this for parsing package versions.
  • psycopg2-binary==2.9.11: The recommended PostgreSQL adapter for Python. Allows your Django app to interact with a PostgreSQL database, which is Heroku’s default.
  • sqlparse==0.5.3: Used by Django for formatting and parsing SQL queries, especially helpful in development and database schema operations.
  • typing_extensions==4.15.0: Provides backported type hints and features to ensure compatibility with current Python typing standards; used by Django and other dependencies.

Preparing Your Application for Production

You’ve already installed most of the required packages as listed in your requirements.txt with the specified versions. Next, let’s add Whitenoise for static file serving in production.

To install Whitenoise, run:

pip install whitenoise

After installing, update your requirements.txt:

pip freeze > requirements.txt

Your updated requirements.txt should now look like this:

asgiref==3.10.0
dj-database-url==3.0.1
Django==4.2.26
gunicorn==23.0.0
packaging==25.0
psycopg2-binary==2.9.11
sqlparse==0.5.3
typing_extensions==4.15.0
whitenoise==<your-installed-version>

(Replace <your-installed-version> with the actual version installed, e.g., whitenoise==6.6.0)

To ensure all dependencies are up to date, run:

pip freeze > requirements.txt

(If you add new packages later, update this file accordingly.)

Step 1: Create the Procfile

Heroku uses a file named Procfile to know how to start your app. In your project’s root directory (where manage.py is), create a file named Procfile (no extension):

web: gunicorn your_project_name.wsgi --log-file -

Replace your_project_name with your Django project’s folder name (the one containing settings.py).

Step 2: Configure settings.py for Heroku

a) Database Configuration

Your database setup should use dj-database-url==3.0.1 and psycopg2-binary==2.9.11 f

(If you add new packages later, update this file accordingly.)

Step 1: Create the Procfile

Heroku uses a file named Procfile to know how to start your app. In your project’s root directory (where manage.py is), create a file named Procfile (no extension):

web: gunicorn your_project_name.wsgi --log-file -

Replace your_project_name with your Django project’s folder name (the one containing settings.py).

Step 2: Configure settings.py for Heroku

a) Database Configuration

Your database setup should use dj-database-url==3.0.1 and psycopg2-binary==2.9.11 for PostgreSQL support on Heroku.

At the top of your settings.py, import the required packages:

import os
import dj_database_url

Update your DATABASES setting:

DATABASES = {
'default': dj_database_url.config(
default=os.environ.get('DATABASE_URL')
)
}

b) Static Files (for Heroku)

Heroku does not serve static files out of the box, so configure Django to collect static files:

At the bottom of settings.py, add:

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

For efficient static file serving and compression in production, you can use Whitenoise or handle this with your own middleware. If you add whitenoise , include in settings.py:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ... other middleware ...
]
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # For Whitenoise

c) Allowed Hosts

Set your live app’s domain in ALLOWED_HOSTS:

ALLOWED_HOSTS = ['your-app-name.herokuapp.com', 'localhost', '127.0.0.1']

d) SECRET_KEY and DEBUG


Your secret key and debug flag should be set using environment variables. For example:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your-development-secret-key')
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'

Set these on Heroku:

heroku config:set DJANGO_SECRET_KEY=your-production-secret-key
heroku config:set DJANGO_DEBUG=False

Inside the Python shell, run:

import secrets

print(secrets.token_urlsafe())

Example output:

n8qfLqL3yWjP6bKz7aQx9v3sD0eFjH2R1tUoG5pV

Replace <your-production-secret-key> with the generated key:

heroku config:set DJANGO_SECRET_KEY="n8qfLqL3yWjP6bKz7aQx9v3sD0eFjH2R1tUoG5pV"
heroku config:set DJANGO_DEBUG=False

Setting up Heroku

WARNING: heroku dyno cost $5 and database $5

Before deploying your Django project, you’ll need to set up Heroku on your system.

1. Create a Heroku Account

Go to https://signup.heroku.com/ and sign up for a free Heroku account if you haven’t already.

2. Install the Heroku CLI

To install the Heroku Command Line Interface (CLI) on Cloud9 or most Linux environments, download and run the official install script:

curl https://cli-assets.heroku.com/install.sh | sh

# check versioon
heroku --version

For details and troubleshooting, see Heroku’s CLI documentation.

3. Log In to Heroku

You can log in to Heroku using a Heroku API token, which is especially useful if standard login is unavailable in your environment.

To create an API token:

  1. Go to your Heroku Account Settings.
  2. Scroll down to the API Key section.
  3. Click Reveal to see your API key, or Regenerate API Key if needed.
  4. Copy the API key.

To log in with your API token, use:

heroku login -i

When prompted for your email, enter your Heroku account email. When prompted for your password, paste the API key instead.

This method allows you to authenticate securely without needing a browser.

4. Verify the Setup

heroku --version

You should see the Heroku CLI version output in your terminal.


Creating a Project in Heroku

Before deploying, you’ll need to create a new project (called an “app”) on Heroku and set up your environment for deployment.

1. Create Your Heroku App

From your project’s root directory, use the Heroku CLI to create a new app:

heroku create your-unique-app-name

Replace your-unique-app-name with a unique name you choose. If you skip the name, Heroku will generate a random one for you. This command also adds a heroku Git remote to your local repository, which you’ll use to deploy your code.

2. Review Your Heroku App

To see a list of your Heroku apps, you can run:

heroku apps

To open your app’s dashboard in the browser:

heroku dashboard

3. Set Up Environment Variables (Optional)

You’ll often need to set environment variables, such as DEBUG, SECRET_KEY, or any API keys. Use the CLI to add them:

heroku config:set DJANGO_SECRET_KEY='your-production-secret-key'
heroku config:set DEBUG=0

Add any additional variables your app needs.


Deploying to Heroku

Step 3: Install the Heroku CLI and Log In

Start by installing the Heroku CLI and logging in:

sudo snap install --classic heroku
heroku login

Step 4: Create a Heroku App

Create a new Heroku application:

heroku create your-unique-app-name

This sets up a remote Git repository for deployment.

Step 5: Push Your Code to Heroku

Add and commit your changes:

git add .
git commit -m "Prepare for Heroku deployment"

Deploy by pushing to Heroku:

git push heroku main

(If your branch is master, use git push heroku master.)

Check Dyno

heroku ps -a <your-app-name>

Check database

heroku addons

Check Heroku info

heroku info -a <your-app-name>

Check webURL for site address.

Step 6:create datasets

On Heroku, apply your database migrations:

eroku addons:create heroku-postgresql:essential-0

Step 6: Run Database Migrations

On Heroku, apply your database migrations:

heroku run python manage.py migrate

Step 7: Create a Superuser

To use Django admin:

heroku run python manage.py createsuperuser

Final Checks and Troubleshooting

Open your deployed application:

heroku open

Visit /admin and log in with your superuser credentials.

Troubleshooting:

  • If you see an error page, view logs with:heroku logs –tail
  • Verify requirements: all packages should match the versions in requirements.txt.
  • Static files issue? If using Whitenoise, ensure it is in both requirements.txt and MIDDLEWARE. Otherwise, consider Heroku’s static files buildpack or another solution.
  • Database problems? Check you’re using dj-database-url==3.0.1 and that migrations ran.

Conclusion

Great job! Your Django blog is now deployed to Heroku using the exact package versions you require. This workflow provides a reliable, repeatable process—just update your requirements.txt if you add new dependencies and follow these steps to deploy with confidence.


Meta Title: Deploy Django to Heroku: A Step-by-Step Guide (Part 3)
Meta Description: Learn how to deploy your Django blog to Heroku with specific package versions, including dj-database-url, gunicorn, and more. This guide covers configuration and deployment matched to your requirements.

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *