Deploying Django on Heroku 🎯

beginner
24 min

Deploying Django on Heroku 🎯

Welcome to this comprehensive tutorial on deploying Django applications on Heroku! In this lesson, we'll guide you through the process of setting up, configuring, and deploying your first Django project on Heroku.

Prerequisites πŸ“

Before we dive into deploying, let's make sure you have the following tools installed:

  1. Python 3.x (We recommend using Python 3.8 or 3.9)
  2. Pip (Python package installer)
  3. Git (Version control system)
  4. Node.js (For Procfile build steps)

Creating a Django Project πŸ’‘

First, let's create a new Django project. Open your terminal and run:

bash
django-admin startproject my_django_app

Replace my_django_app with the name of your project.

Navigate into the project directory:

bash
cd my_django_app

Installing Django on Heroku πŸ“

Heroku uses the requirements.txt file to manage dependencies. Let's create one:

bash
pip freeze > requirements.txt

Now, add Django to the requirements file:

Django==3.2.7

Preparing for Deployment πŸ’‘

Heroku requires a Procfile to run our Django app. Create a new file named Procfile in the project root with the following content:

web: gunicorn my_django_app.wsgi

Next, we need to set up database and environment variables. Create a .env file in the project root:

DATABASE_URL=<your_heroku_database_url> SECRET_KEY=<your_secret_key>

Replace <your_heroku_database_url> with your Heroku PostgreSQL database URL and <your_secret_key> with a secret key for your project.

Creating a Git Repository πŸ’‘

Initialize a Git repository, commit your changes, and create a new GitHub repository for your project.

bash
git init git add . git commit -m "Initial commit"

Now, copy the GitHub repository URL and set it as the origin of your local repository:

bash
git remote add origin <your_github_repository_url>

Deploying to Heroku πŸ’‘

Create a new Heroku app and connect it to your GitHub repository. You can do this through the Heroku CLI or the web dashboard.

Next, add Heroku as a remote:

bash
heroku git:remote -a <your_heroku_app_name>

Now, push your local repository to Heroku:

bash
git push heroku master

Setting Up Migrations πŸ’‘

Heroku will automatically detect the changes in your Django project and run the migrations. However, you can force a migration by running:

bash
heroku run python manage.py migrate

Running Your Django App on Heroku πŸ’‘

To verify that your Django app is running on Heroku, use the following command:

bash
heroku open

Quiz πŸ“

Quick Quiz
Question 1 of 1

What should be added to the `Procfile` to run Gunicorn with Django?

Congratulations! You've successfully deployed a Django app on Heroku. Keep exploring, learning, and building! 🌟